使用list monad实现每位数的计数器

Aid*_*lly 2 monads haskell list-comprehension

所以,我在这里看问题,为问题构建了一个相当丑陋的解决方案.在尝试清理时,我开始调查列表推导和列表monad.我决定要做的是使用list monad实现一个每位数的计数器.给定一个输入的数字序列[1, 2],我想生成一个类似于下面的输出序列:

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

也就是说,我将遍历该范围内列表中所有元素的所有可能值.

haskell.org 列表monad文档说:

绑定函数应用于输入列表中的所有可能值,并将结果列表连接起来以生成所有可能结果的列表.

大!看起来很完美......这是我为编写解决方案而编写的代码:

count :: [Integer] -> [[Integer]]
count [] = []
count (x:xs) =
  -- get all possible sequences for the remaining digits
  let
    remDigits :: [[Integer]]
    remDigits = count xs
  in
  -- pull out a possible sequence for the remaining digits
  do nextDigits <- remDigits
     -- pull out all possible values for the current digit
     y <- [0..x]
     -- record that "current digit" : "remaining digits" is
     -- a valid output.
     return (y:nextDigits)
Run Code Online (Sandbox Code Playgroud)

但是count用任何东西调用会产生空列表,我不知道为什么.我错过了什么?

eph*_*ent 8

count = sequence . map (enumFromTo 0)
Run Code Online (Sandbox Code Playgroud)

是的,它真的很简单.试试看 :)


new*_*cct 8

甚至更短

count = mapM (enumFromTo 0)
Run Code Online (Sandbox Code Playgroud)