Haskell adds two matches to the list template

So I have the following in GHCI

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

The last line gives me: [7,9,11,13,15 *** Exception :: 1: 5-49: non-exhaustive templates in the function list

I'm just trying to add two lists together to one list ... :(

What have I done wrong?

thanks

+6
source share
3 answers

If you want to define a function using pattern matching inside let , you cannot use one allowed for each pattern, as you did, it will simply define two independent functions (the second is the shading of the first).

You need to use one run and split the patterns using linebreaks or, in ghci, where you cannot use linebreaks, semicolons. So:

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

Please do not remember that you still have problems with the "Non-exhaustive match pattern" 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 two templates in which one of the lists is empty!

One final note: it is painful to write multi-line definitions in GHCi - write them in some editor to a .hs file and use :load MyFile.hs and :reload inside GHCi

+14
source

Note that you have a built-in zipWith function for combining two lists by elements with a given function, so you can write

 addList xs ys = zipWith (+) xs ys 

or shorter

 addList = zipWith (+) 
+3
source

Source: https://habr.com/ru/post/897288/


All Articles