FastBatteryCharger
FastBatteryCharger

Reputation: 349

Haskell, sum up two elements of a list with pattern matching?

i am learning the pattern syntax in Haskell and now i have a problem with my small function.

I want to add two elements of a list like in the example:

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]

My Code(i tried to make a pattern for two elements but it says that the patterns are overlapping):

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

It should look like this, but i dont know how to create the pattern for 2 elements:

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

Test:

*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

Upvotes: 1

Views: 678

Answers (2)

chepner
chepner

Reputation: 531165

You can just zip the list with a "shifted" version of itself.

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

Upvotes: 2

alykhank
alykhank

Reputation: 453

You can call g4 on the combination of (y:xs) for your recursive component:

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

Upvotes: 3

Related Questions