exhaustive patterns using if
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
?
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.
链接地址: http://www.djcxy.com/p/43282.html上一篇: 哈斯克尔错误:非
下一篇: 使用if的详尽模式