overpro
overpro

Reputation: 49

Haskell combination of number and bool

In Haskell, when I input a list of ordered number, how can I make a list which has all the possible combination of the number and the bool(either True or False) ?

for example when I input [1,2]
the output is:

[ [(1,False),(2,False)]
, [(1,False),(2,True)]
, [(1,True),(2,False)]
, [(1,True), (2,True)] ]

Upvotes: 0

Views: 415

Answers (3)

karakfa
karakfa

Reputation: 67567

with list comprehensions

[zip [1..] [x,y] | x<-[True,False], y<-[True,False]]

Upvotes: 0

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64750

The list monad might be the easiest to understand:

f xs = do
    bs <- replicateM (length xs) [False, True]  -- Obtain |xs| elements from the set of all possible booleans
    return (zip xs bs)                          -- Pair the elements of each list

With a result of:

Prelude Control.Monad> f [1,2]
[[(1,False),(2,False)],[(1,False),(2,True)],[(1,True),(2,False)],[(1,True),(2,True)]]

Upvotes: 5

ErikR
ErikR

Reputation: 52057

b1 n = sequence $ replicate n [False,True]

b2 xs = map (zip xs) (b1 (length xs))

Example:

*Main> b2 [1,2]
[[(1,False),(2,False)],[(1,False),(2,True)],[(1,True),(2,False)],[(1,True),(2,True)]]

Upvotes: 2

Related Questions