Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Non-exhaustive patterns in function when using an example from a haskell book

I tried to run this code:

product (x:xs) = x * product xs
product [] = 1


sum [] = 0
sum (n:ns) = n + sum ns

sum [2,3,6]


product [2,3,4]

and for some reason it is giving me the "Non-exhaustive patterns in function" error, for both sum and product definitions.

Why are those patterns non-exhaustive? I’ve defined the functions on an empty list and of a list of 1 or more elements. What more does it need?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using The Glorious Glasgow Haskell Compilation System, version 9.2.4 and these examples are from the book by Graham Hutton. Has something changed in the Haskell compiler since 2016 (when the book was written).

>Solution :

In GHCi, you need to use the special commands :{ and :} to enclose a multiline definition; otherwise, as pointed out in the comments, your second line just redefines the (partial) function you defined in the first line.

Prelude> :{
Prelude| product (x:xs) = x * product xs
Prelude| product [] = 1
Prelude| :}
Prelude>

Notice that after entering :{, the prompt switches from > to | to indicate that you are in the process of entering a multiline definition.

Alternatively, you can write your code in a .hs file, and :load it in GHCi. Doing so ensures that all the lines for a definition are considered.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading