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?
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).
CodePudding user response:
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.