Template matching on Ints

I am starting to learn Haskell and I wanted to know if you can map an image Int

like this:

 add x 0 = x
 add x (1 + y) = 1 + x  + add x y,

      

Or maybe this way:

 add x 0 = x
 add x (successor y) = 1 + x + add x y

      

+3


source to share


3 answers


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.

+13


source


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.

+2


source


The formatting of your code is a bit off, so it's hard to figure out what you're asking, but you can use pattern matching to type Int. Example:

add x 0 = x
add x y = x + y

      

0


source







All Articles