Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading