views:

221

answers:

1

I am fairly new to Haskell but do get most of the basics. However there is one thing that I just cannot figure out. Consider my example below:

example :: Int -> Int
example (n+1) = .....

The (n+1) part of this example somehow prevents the input of negative numbers but I cannot understand how. For example.. If the input were (-5) I would expect n to just be (-6) since (-6 + 1) is (-5). The output when testing is as follows:

Program error: pattern match failure: example (-5)

Can anyone explain to me why this does not accept negative numbers?

Thanks in advance.

+10  A: 

That's just how n+k patterns are defined to work:

Matching an n+k pattern (where n is a variable and k is a positive integer literal) against a value v succeeds if x >= k, resulting in the binding of n to x - k, and fails otherwise.

The point of n+k patterns is to perform induction, so you need to complete the example with a base case (k-1, or 0 in this case), and decide whether a parameter less than that would be an error or not. Like this:

example (n+1) = ...
example 0 = ...

The semantics that you're essentially asking for would be fairly pointless and redundant — you could just say

example n = let n' = n-1 in ...

to achieve the same effect. The point of a pattern is to fail sometimes.

jleedev
My lecturer used it without explaining how or why it worked. You have explained it well. Thank You.
Jonathan Pike