因此,我在看問題here,併爲此問題構建了一個相當難看的解決方案。在嘗試清理它時,我開始調查列表解析和列表monad。我決定要使用list monad實現一個按位數的計數器。鑑於數字的輸入序列,[1, 2]
,我想產生看起來是這樣的輸出序列:使用列表monad實現每位數計數器
[ [ 0, 0],
[ 0, 1 ],
[ 0, 2 ],
[ 1, 0 ],
[ 1, 1 ],
[ 1, 2 ] ]
也就是說,我會遍歷所有元素的所有可能的值,在該範圍內的清單。
的haskell.org list monad documentation說:
結合的函數被施加到輸入列表中的所有可能值和所得到的列表被級聯以產生所有可能的結果的列表。
太棒了!看上去很完美......這是我寫的生產解決方案的代碼:
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
與任何產生空列表,我不知道爲什麼。我錯過了什麼?
如果您只是將您的基本情況更改爲'count [] = [[]]',則此代碼有效。 – ephemient 2009-12-06 19:17:32
實際上,這正是我所尋找的答案......我發現我的問題是,在基本情況下,單子列表中沒有解決方案,所以沒有任何可以解決的問題。 CBFraser的回答如下,但你的解決方案更接近我原先的想法。 – 2009-12-06 20:02:25