如何在Haskell中汇总扩展列表的中间元素? [英] How can I sum the middle elements of an expanding list in Haskell?
问题描述
到目前为止,我知道如何从末端扩展列表,但是由于第一个条件(使单例增加一倍),它们最终变得倍增.代码像这样有意义吗?
So far I know how to expand a list from its ends, but they end up getting doubled because of the first condition, which is to double a singleton. Would it make sense for the code to be like this:
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)
对我来说,要处理其输出:
And for me to work on its output:
[1,1,2,2,3,3] from [1,2,3]
instead of [1,3,5,3]
后一个是我的愿望吗?这是我找到两个元素列表的临时解决方案的方法:
The latter being my desire? Here's how I got to a temporary solution for a list of two elements:
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]
推荐答案
基本上,所有您想要计算输入列表和其转换版本之间的按组件和:
Basically, all you want to compute component-wise sums between your input list and a shifted version of it:
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
Fill each empty slot with a 0 (0:x
and x++[0]
), and you just need zipWith
> (\x -> zipWith (+) (0:x) (x++[0])) [1,2,3]
[1,3,5,3]
这篇关于如何在Haskell中汇总扩展列表的中间元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!