如果您想要處理輸入的靈活性,這些輸入不只是列表[1,11]
:
λ> import Control.Applicative (liftA2)
λ> let sumsOfCombinations xs = (:[]) . sum <$> foldr (liftA2 (:)) [[]] xs
你可以通過它的數字列表中的任何名單:
λ> sumsOfCombinations' [[0,100],[-1,0,1],[0,1000]]
[-1,999,0,1000,1,1001,99,1099,100,1100,101,1101]
包括,但不限於,你的例子:
λ> sumsOfCombinations $ replicate 3 [1,11]
[[3],[13],[13],[23],[13],[23],[23],[33]]
λ> sumsOfCombinations $ replicate 4 [1,11]
[[4],[14],[14],[24],[14],[24],[24],[34],[14],[24],[24],[34],[24],[34],[34],[44]]
下面是它的類型:
λ> :t sumsOfCombinations
sumsOfCombinations :: (Num b, Foldable t) => t [b] -> [[b]]
A寫的,sumsOfCombinations
給你你正在尋找的確切輸出。不過,我不認爲這是必要返回一個列表的列表,所以我會選擇:
λ> let sumsOfCombinations' xs = sum <$> foldr (liftA2 (:)) [[]] xs
λ> :t sumsOfCombinations'
sumsOfCombinations' :: (Num b, Foldable t) => t [b] -> [b]
λ> sumsOfCombinations' $ replicate 3 [1,11]
[3,13,13,23,13,23,23,33]
注意,您可以從每一種提取助手,讓您從列表中元素的組合:
λ> let combinations = foldr (liftA2 (:)) [[]]
λ> combinations [[1,2],[3,4],[5,6]]
[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]
,那麼你必須:
sumsOfCombinations xs = (:[]) . sum <$> combinations xs
,或者,如果你不需要返回一個列表的列表:
sumsOfCombinations' xs = sum <$> combinations xs
是的,謝謝 - 尋找... nub $ map sum $ sequence [[1,11],[1,11]]等等,因爲它不是monadic ... – Craig