Haskell 数字和布尔的组合

Haskell combination of number and bool

在 Haskell 中,当我输入一个有序数字列表时,我怎样才能创建一个包含数字和布尔值(True 或 False)所有可能组合的列表?

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

[ [(1,False),(2,False)]
, [(1,False),(2,True)]
, [(1,True),(2,False)]
, [(1,True), (2,True)] ]
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)]]

列表 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)]]

具有列表理解

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