Caelan Miron
Caelan Miron

Reputation: 154

pattern matching of negative literals in Haskell

I was trying to understand why n + k patterns were banned in Haskell. A famous post on StackOverflow gives an example of a function as follows:

f 0 = 0
f (n + 5) = 5

Haskell shows an error while matching f 1, f 2, f 3, f 4. I cannot understand why (-1) cannot be matched with n. Firstly, I thought that integers only contain non-negative literals (0,1,..), but Haskell's definition of Int type includes negative literals.

Upvotes: 1

Views: 338

Answers (1)

amalloy
amalloy

Reputation: 92077

Why can't -1 be matched? That's simply how n+k patterns were defined, presumably because it seemed like a good idea at the time. It's natural to use induction for natural numbers, so why not define our cool n+k patterns to work for naturals? From the Haskell report:

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. Again, the functions >= and - are overloaded, depending on the type of the pattern. The match diverges if the comparison diverges.

The fact that you found this surprising is probably one reason why n+k patterns were removed. Another is that there's no need for them: you can easily translate any n+k pattern into a pattern not using this feature.

Upvotes: 4

Related Questions