[英]How can I find the middle element of the list in a function in 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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.