1

I am writing in Haskell a function that gets two lists of type Int and adds the values of one list to that one of the other.

for example: addElements [1,2,3] [4,5,6] will give the output: [5,7,9]

my function so far:

addElements :: [Int] -> [Int] -> [Int]
addElements [] [] = []
addElements x:xs [] = x:xs
addElements [] y:ys = y:ys
addElements x:xs y:ys = [x+y] ++ addElements xs ys

I keep getting the error:

Parse error in pattern: addElements Failed, modules loaded: none

I do not get any additional information - what have I done wrong?

jublikon
  • 3,427
  • 10
  • 44
  • 82

2 Answers2

8

You need parentheses around your patterns. It should be (x:xs), not x:xs on its own. That's what is causing the compiler confusion.

addElements :: [Int] -> [Int] -> [Int]
addElements [] [] = []
addElements (x:xs) [] = x:xs
addElements [] (y:ys) = y:ys
addElements (x:xs) (y:ys) = [x+y] ++ addElements xs ys
Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
1

Not an answer to the OP, but I just wanted to point out that the patterns can be simplified to:

addElements :: [Int] -> [Int] -> [Int]
addElements xs [] = xs
addElements [] ys = ys
addElements (x:xs) (y:ys) = (x+y) : addElements xs ys
pat
  • 12,587
  • 1
  • 23
  • 52