How to generalize input in Haskell

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:

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?

+4
source share
3 answers

, Haskell . , ; .

, , - ( , ), . ; .

, , dfeuer: boomBangs? ? , , boomBangs , . ( , .)

, , , boomBangs : . 8- , 8- , 16- , 16- , ... , .

- . ( , boom-bang s.) - (, list, Maybe, Either e). (, , -). , , - .

+5

. -: boomBang. boomBangs [2,5,6,7,1] boomBang 7 - no if.

, , .

boomBangs xs = [b | x <- xs, b <- boomBang x]

, .

+5

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"]
+2
source

All Articles