Given:
data TwoInts = TwoInts Int Int
add'em :: TwoInts -> Int
add'em (TwoInts a b) = a+b
is it possible to write add'em
without having to name a
and b
. Something like:
add'em TwoInts = (+) -- (Note: Fails to type check)
Overview. We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.
Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.
Via analogy to tuples,
data TwoInts = TwoInts { fst', snd' :: Int }
we can define an operation for lifting functions of two arguments onto a TwoInt
uncurry' f p = f (fst' p) (snd' p)
Giving us the nice notation:
add'em = uncurry' (+)
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