Template matching on Ints
There is an extension that allows you to do this, but instead you should just match the pattern by y
and subtract 1
manually:
add x y = 1 + x + add x (y - 1)
The extension is called NPlusKPatterns
. If you really want to use it (remember it's deprecated in haskell 2010), you can enable it either by passing a parameter -XNPlusKPatterns
to GHC or by placing it {-# LANGUAGE NPlusKPatterns #-}
at the beginning of the file.
source to share
Pattern matching is not an arbitrary case analysis. This is a disciplined but limited form of case analysis, where cases are the constructors of the data type.
In the specific case of integers matching patterns, constructors are assumed to be integers. Thus, you can use integer values ββas examples for pattern matching:
foo 0 = ...
foo 2 = ...
foo x = ...
But you cannot use arbitrary expressions. The following code is illegal:
foo (2 * x) = ...
foo (2 * x + 1) = ...
You may know that ever an integer has either a form 2 * x
or 2 * x + 1
. But the type system does not know.
source to share