3
votes

On the first code example in "Programming in Haskell" the following is stated:

Recall the function sum used earlier in this chapter, which produces the sum of a list of numbers. In Haskell, sum can be defined using two equations:

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

Immediately, this code fails both in the ghci interpreter and upon compilation with the error: "Non-exhaustive patterns in function sum"

After further research it seems this is because the case of a single number isn't covered. What gets me is the next few examples in the book also fail to work.

Am I missing something here? The book was released rather recently in 2016 and I can't find anyone else complaining aout this.

1

1 Answers

10
votes

When you enter the first clause of the definition of sum and press enter GHCI assume that you've finished and it should evaluate the program. The program

sum [] = 0

Doesn't specify what to do if the argument is non-empty, so you get the "non-exhaustive patterns" error.

GHCI has :{ and :} commands to allow you to enter multiple clauses (or other code that spans multiple lines:

Prelude> :{
Prelude| sum [] = 0
Prelude| sum (n:ns) = n + sum ns
Prelude| :}
Prelude> sum []
0
Prelude> 

In general I would recommend saving the definitions you are working with in a file and loading that file in GHCI. Then you can :reload when you make some changes and call your function/s with various arguments to see what happens.