Reputation: 3080
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?
Upvotes: 5
Views: 169
Reputation: 2059
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. :)
Upvotes: 4