Haskell,用模式匹配总结列表的两个元素?

时间:2016-05-03 20:25:59

标签: list haskell pattern-matching

我正在学习Haskell中的模式语法,现在我的小函数出现了问题。

我想在示例中添加列表的两个元素:

input 1: [1,2,3,4,5],  output2: [3,5,7,9]

input 2: [1,2,3,4,5,6],  ouput 2: [3,5,7,11]

我的代码(我试图为两个元素制作一个模式,但它说模式是重叠的):

g4 [] = []
g4 [x] = [] 
-- g4 (x:y:xs) = x+y: g4 xs
g4 (x:y:z:xs) = x+y:y+z: g4 (xs)

应该看起来像这样,但我不知道如何为2个元素创建模式:

g1 [1,2,3,4,5]
 = 1+2 : 2+3 : g1 [3,4,5]
          = 3+4 : 4+5 : g1 [5]
               = []


g1 [1,2,3,4,5,6]
 = 1+2 : 2+3 : g1 [3,4,5,6]
          = 3+4 : 4+5 : g1 [5,6]  
                = 5+6

测试:

*Main> g4 [1,2,3]
[3,5] -- worked
*Main> g4 [1,2,3,4]
[3,5,4] -- did not work
*Main> g4 [1,2,3,4,5]
*** Exception: Test.hs:(127,1)-(130,32): Non-exhaustive patterns in function g4 -- didnt work

[3,5*Main> g4 [1,2,3,4,5,6]
[3,5,9,11] -- worked

2 个答案:

答案 0 :(得分:3)

您可以针对递归组件的g4组合调用(y:xs)

g4 [] = []
g4 [x] = []
g4 (x:y:xs) = x+y : g4 (y:xs)

答案 1 :(得分:2)

您可以使用" shift"本身的版本。

g4 xs = zipWith (+) xs (tail xs)