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
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
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
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 (+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With