Metalcoder
Metalcoder

Reputation: 2262

Non-exhaustive patterns using if-then-else

I have the following function:

myMaximum [] = error "There is no such thing as 'maximum' in an empty list."
myMaximum [x] = x
myMaximum (x:xs) = if x >= tailMax
                    then x
                    else tailMax
                where tailMax = myMaximum xs

I works just fine when I run myMaximum [1..5], but it throws the error defined on the first line when I run myMaximum [5..1]. If I take the first line out, it will complain that there is a non-exhaustive pattern on myMaximum. But why this pattern is non-exhaustive? And how calling it with [1..5] works just fine and [5..1] apparently results in empty list argument to myMaximum?

Upvotes: 2

Views: 181

Answers (1)

Sebastian Redl
Sebastian Redl

Reputation: 71979

This isn't about your function. It's about range notation. Type [5..1] in ghci, and you'll find that you get an empty list.

Haskell range notation defaults to adding one at each step unless you explicitly change it using the [first,second..last] notation. Use [5,4..1] to get the behavior you're looking for.

If you remove the first version of your function, the pattern is non-exhaustive because no version of your function can match the empty list then.

Upvotes: 10

Related Questions