6

So here I have the following on GHCI

>let addlist [] [] = []
>let addlist (a:as) (b:bs) = (a+b) : addlist as bs
>let x = [1..5]
>let y = [6..10]
>addlist x y

The last line gives me: [7,9,11,13,15*** Exception: :1:5-49: Non-exhaustive patterns in function addlist

I am merely trying to add two list together into one list...:(

What did I do wrong?

Thanks

1
  • 4
    I don't want to detract from sepp2k's answer, but in this case try also let addlist = zipWith (+) Commented Sep 14, 2011 at 8:10

3 Answers 3

14

Please not that you still have problems with "Non-exhaustive pattern-match" if the lists are not the same size! Here is a solution that works for all cases:

addList [] _ = []
addList _ [] = []
addList (a:as) (b:bs) = (a+b) : addList as bs

not the two patterns where either list is empty!

And one final note: it's a pain to write multi-line definitions in GHCi - write them in some editor into a .hs file and use :load MyFile.hs and :reload inside GHCi

Sign up to request clarification or add additional context in comments.

3 Comments

It's less of a pain if you use the multi-line syntax (:{ ... :}), but it's still a better idea to use an editor.
Wouldn't you want addList [] ys = ys and addlist xs [] = xs?
depends on how you see it - if I add [1,2,3] and [4,5,6,7] - should it be [5,7,9] or [5,7,9,7]? I don't like the second answer so I stay with mine ....
13

If you want to define a function using pattern matching inside a let, you can't use one let per pattern as you did - that will simply define two independent functions (the second one shadowing the first).

You need to use a single let and separate the patterns using linebreaks or, in ghci where you can't use linebreaks, semicolons. So:

let addlist [] [] = []; addlist (a:as) (b:bs) = (a+b) : addlist as bs

2 Comments

EclipseFP is not bad - but I do most stuff with Notepad++ but I guess the usual answer will be Emacs or VI ;)
Please note that this will solve your problem at hand with GCHi but will fail with lists of different sizes
3

Note that you have a built-in function zipWith for merging two lists element-wise with a given function, so you can write

addList xs ys = zipWith (+) xs ys

or shorter

addList = zipWith (+)

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.