Haskell组合数和布尔

时间:2015-01-06 23:19:03

标签: haskell combinations

在Haskell中,当我输入有序数字列表时,如何创建一个列表,其中包含数字和bool的所有可能组合(True或False)?

例如,

当我输入[1,2]
输出是:

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

3 个答案:

答案 0 :(得分:5)

列表monad可能是最容易理解的:

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

结果:

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

答案 1 :(得分:2)

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

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

示例:

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

答案 2 :(得分:0)

列表推导

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