Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell pattern match numbers (deconstruction)

Can pattern matching in Haskell be used for deconstructing numbers in this way:

f (n + 1) = n

I expect predicessor for ex: f 6 = 5, f 5 = 4 etc.

I found such kind of pattern matching usage here: https://wiki.haskell.org/Continuation

 facCPS :: a -> (a -> r) -> r
 facCPS 0 k = k 1
 facCPS n'@(n + 1) k = facCPS n $ \ret -> k (n' * ret)
 facCPS 4 (+ 2) :: Integral a => a

but in my ghci it does not work:

Prelude> f (n + 1) = n :4:12: error: Parse error in pattern: n + 1

Maybe some options need to be added? can I use somehow use pattern matching in this way?

like image 389
Evg Avatar asked Oct 30 '20 09:10

Evg


People also ask

How do you do pattern matching in Haskell?

You do that by putting a name and an @ in front of a pattern. For instance, the pattern xs@(x:y:ys). This pattern will match exactly the same thing as x:y:ys but you can easily get the whole list via xs instead of repeating yourself by typing out x:y:ys in the function body again.

What is pattern matching explain with example?

Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.

What is XS Haskell?

x:xs is simply another notation for lists in Haskell, where x represents the head of the list and xs (pronounced exes) represents the tail. So, again for the list [1, 2, 3], x would be 1, whilst xs would be [2, 3].

What is pattern matching in OCaml?

Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.


1 Answers

Using the example from the wiki that you quoted:

{-# LANGUAGE NPlusKPatterns #-}
fac :: Integral a => a -> a
fac 0 = 1
fac n'@(n + 1) = n' * fac n

This was removed from the language in 2010, but Haskell remains a very configurable language. :)

like image 52
Marc Talbot Avatar answered Oct 10 '22 23:10

Marc Talbot