Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my Haskell function accept negative numbers?

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?

like image 769
Jonathan Pike Avatar asked Feb 11 '10 23:02

Jonathan Pike


1 Answers

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.

like image 165
Josh Lee Avatar answered Nov 02 '22 05:11

Josh Lee