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?
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.
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.
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].
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.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With