9

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?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
Jonathan Pike
  • 93
  • 1
  • 3
  • 8
    Note that `n+k` patterns will be removed from the next version of the Haskell language specification (Haskell 2010). As far as I know, they are rarely used in practice (although I'm sure someone will find an anecdotal example). So I would suggest not using them. – Tom Lokhorst Feb 12 '10 at 00:16

1 Answers1

10

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.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275