Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell add two list pattern matching

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

like image 401
nobody Avatar asked Sep 14 '11 07:09

nobody


3 Answers

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

like image 153
Random Dev Avatar answered Oct 16 '22 22:10

Random Dev


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
like image 20
sepp2k Avatar answered Oct 16 '22 22:10

sepp2k


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 (+)
like image 38
Landei Avatar answered Oct 16 '22 22:10

Landei