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?

2
  • 3
    I think you need parenthesis around the x:xs and y:ys pattern matches. Commented Feb 27, 2017 at 13:22
  • Possible duplicate of Haskell: Parse error in pattern Commented Sep 6, 2017 at 7:43

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.