Reputation: 81
I am a beginner in learning Haskell, and I wanted to know if you could pattern match on Int
s like so:
add x 0 = x
add x (1 + y) = 1 + x + add x y,
Or maybe in this way:
add x 0 = x
add x (successor y) = 1 + x + add x y
Upvotes: 3
Views: 224
Reputation: 103
The formatting of your code is a bit off so it is difficult to know what you're asking but you can using pattern matching for input of type Int. An example would be
add x 0 = x
add x y = x + y
Upvotes: 0
Reputation: 19772
Pattern matching isn't arbitrary case analysis. It's a disciplined, but limited form of case analysis, where the cases are the constructors of a data type.
In the specific case of pattern matching integers, the constructors are taken to be the integer values. So you can use integer values as the cases for pattern-matching:
foo 0 = ...
foo 2 = ...
foo x = ...
But you can't use arbitrary expressions. The following code is illegal:
foo (2 * x) = ...
foo (2 * x + 1) = ...
You may know that ever integer is either of the form 2 * x
or 2 * x + 1
. But the type system doesn't know.
Upvotes: 2
Reputation: 796
There is an extension that lets you do that, but instead you should simply pattern match on 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 (keep in mind it's deprecated in haskell 2010), it can be enabled by either passing a -XNPlusKPatterns
parameter to GHC, or putting a {-# LANGUAGE NPlusKPatterns #-}
at the top of your file.
Upvotes: 13