Haskell组合数和布尔

ove*_*pro 0 combinations haskell

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

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

[ [(1,False),(2,False)]
, [(1,False),(2,True)]
, [(1,True),(2,False)]
, [(1,True), (2,True)] ]
Run Code Online (Sandbox Code Playgroud)

Tho*_*son 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
Run Code Online (Sandbox Code Playgroud)

结果是:

Prelude Control.Monad> f [1,2]
[[(1,False),(2,False)],[(1,False),(2,True)],[(1,True),(2,False)],[(1,True),(2,True)]]
Run Code Online (Sandbox Code Playgroud)

  • 或者:`f = mapM(\ x - > [(x,False),(x,True)])`. (4认同)