I am just starting to learn Haskell, and I use learnyouahaskell.com as a guide, and I use ghcias an interpreter. I have a question about lists. On a website, they define a function:
ghci
boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x]
This only works for lists. Taking into account that
boomBangs x = [ if x < 10 then "BOOM!" else "BANG!" | odd x]
Works only for individual inputs, i.e.
boomBangs 21 boomBangs 7
Is there a way to write this statement, so it doesn’t matter if I put
boomBangs [2,5,6,7,1]
or
boomBangs 7
without the need for an if statement?
, Haskell . , ; .
, , - ( , ), . ; .
, , dfeuer: boomBangs? ? , , boomBangs , . ( , .)
boomBangs
, , , boomBangs : . 8- , 8- , 16- , 16- , ... , .
- . ( , boom-bang s.) - (, list, Maybe, Either e). (, , -). , , - .
Maybe
Either e
. -: boomBang. boomBangs [2,5,6,7,1] boomBang 7 - no if.
boomBang
boomBang 7
if
, , .
boomBangs xs = [b | x <- xs, b <- boomBang x]
, .
You can implement different types of behavior for different types using type classes. For instance:
class BoomBang a where boomBang :: a -> [String] instance BoomBang Integer where boomBang x = [if x < 10 then "BOOM" else "BANG" | odd x] instance BoomBang a => BoomBang [a] where boomBang xs = xs >>= boomBang
In ghci:
> boomBang 7 ["BOOM"] > boomBang [2,5,6,7,1] ["BOOM","BOOM","BOOM"]