所以,我在这里查看了这个问题,并为这个问题构建了一个相当丑陋的解决方案。在尝试清理它时,我开始研究列表推导和列表单子。我决定做的是使用 list monad 实现一个每位数的计数器。给定一个数字输入序列[1, 2]
,我想生成一个输出序列,如下所示:
[ [ 0, 0],
[ 0, 1 ],
[ 0, 2 ],
[ 1, 0 ],
[ 1, 1 ],
[ 1, 2 ] ]
也就是说,我将遍历该范围内列表中所有元素的所有可能值。
haskell.org list 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)
但是用任何东西调用count
都会产生空列表,我不知道为什么。我错过了什么?