如何在 Haskell 中对扩展列表的中间元素求和?
How can I sum the middle elements of an expanding list in Haskell?
到目前为止,我知道如何从末端扩展列表,但由于第一个条件,即使单例加倍,它们最终会加倍。像这样的代码是否有意义:
sumExpand :: [Integer] -> [Integer]
sumExpand l = expand l []
where
expand [] a = a
expand (x:[]) a = x: expand [] (x:a)
expand (x:xs) a = expand (x:a) (expand xs a)
让我处理它的输出:
[1,1,2,2,3,3] from [1,2,3]
instead of [1,3,5,3]
后者是我的愿望?以下是我如何找到一个包含两个元素的列表的临时解决方案:
expand (x:xs) a = x: tail (expand (map (x+) xs) (last xs:a))
输出:
*Main> sumExpand [1,2]
[1,3,2]
*Main> sumExpand [1,2,3]
[1,7,4,3]
编辑:基本上,我希望算法像这样工作:[a, b, c] => [a, a+b, b+c, c]
基本上,所有你想计算输入列表和它的移位版本之间的分量总和:
a b c d e
a b c d e
---------------------------
a a+b b+c c+d d+e e
用 0 填充每个空位(0:x
和 x++[0]
),您只需要 zipWith
> (\x -> zipWith (+) (0:x) (x++[0])) [1,2,3]
[1,3,5,3]
到目前为止,我知道如何从末端扩展列表,但由于第一个条件,即使单例加倍,它们最终会加倍。像这样的代码是否有意义:
sumExpand :: [Integer] -> [Integer]
sumExpand l = expand l []
where
expand [] a = a
expand (x:[]) a = x: expand [] (x:a)
expand (x:xs) a = expand (x:a) (expand xs a)
让我处理它的输出:
[1,1,2,2,3,3] from [1,2,3]
instead of [1,3,5,3]
后者是我的愿望?以下是我如何找到一个包含两个元素的列表的临时解决方案:
expand (x:xs) a = x: tail (expand (map (x+) xs) (last xs:a))
输出:
*Main> sumExpand [1,2]
[1,3,2]
*Main> sumExpand [1,2,3]
[1,7,4,3]
编辑:基本上,我希望算法像这样工作:[a, b, c] => [a, a+b, b+c, c]
基本上,所有你想计算输入列表和它的移位版本之间的分量总和:
a b c d e
a b c d e
---------------------------
a a+b b+c c+d d+e e
用 0 填充每个空位(0:x
和 x++[0]
),您只需要 zipWith
> (\x -> zipWith (+) (0:x) (x++[0])) [1,2,3]
[1,3,5,3]