2

I am trying to implement a function that sums the contents of two lists. Here is my code:

sum'' :: Num a => [a] -> [a] -> [a]
sum'' [] [] = []
sum'' (x:xs) (y:ys) = (x + y) : sum'' xs ys

If I type in:

sum'' [1,2,3] [4,5,6]

I get [5,7,9], which is what I want. What I am having trouble with is different list sizes. If I type in:

sum'' [] [1,2,3]

I want it to return []. Or

sum'' [1,2] [4,5,6]

I want it to return [5,7]. I am getting this error and do not know why: Non-exhaustive patterns in function sum''.

Any help would be much appreciated.

1
  • 2
    Turning on warnings with the -Wall flag makes GHC warn about the missed cases at compile time. Recommended. Commented Oct 17, 2017 at 7:40

2 Answers 2

4

When defining sum'', you have defined what it means for two empty lists, and for two non-empty lists, but you haven't defined what it means for two lists, only one of which is empty. This is what the compiler is telling you via that error message.

Simply add definitions of what sum'' means whenever left list is empty and the right list is not, and vice versa:

sum'' (x:xs) [] = ...
sum'' [] (y:ys) = ...
Sign up to request clarification or add additional context in comments.

5 Comments

And, as a cute trick, you could consider sum'' (x:xs) (y:ys) = ...; sum _ _ = ... if your [] [], (x:xs) [], and [] (y:ys)] clauses all return the same thing.
@Fyodor Soikin Thank you for the help, but I am still confused as to how do the second part of the question. sum'' [1,2] [4,5,6] returns only [5,7] and drops the 6 in the second list
@DanielWagner Would you happen to know how do the second part of the question. sum'' [1,2] [4,5,6] returns only [5,7] and drops the 6 in the second list. Not literally do it, but any guidance is appreciated. I tried doing this : sum _ _ = ... if your [] [], (x:xs) [], and [] (y:ys)], but it only gave me an error. All the clauses return the same thing.
@legoniko If one of the lists is shorter, the recursion will ultimately reach the case where one is empty and the other one isn't. You need to define what the result is in those two cases in order to get what you want.
@molbdnilo Thank you! I made a grammatical error and that is why it was not working. It is nice to know the reasoning behind the code. Thank you again!
0

Well in Haskell, actually for what you need there is the ZipList type and you may use it to simply do as follows;

import Control.Applicative

addLists :: Num a => [a] -> [a] -> [a]
addLists xs ys = getZipList $ (+) <$> ZipList xs <*> ZipList ys

*Main> addLists [3] [1,2,3]
[4]

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.