What is a 'nested' pattern in Haskell. I hear the term everywhere but am not sure what the it actually means. How would you define it? Any examples?
Thanks in advance.
EDITED TO ADD: (as quoted in textbook on request)
"Patterns can contain literals and nested patterns, as in the examples:
addPair (0,y) = y
addPair (x,y) = x+y
shift :: ((Int,Int),Int) -> (Int,(Int,Int))
shift ((x,y),z) = (x,(y,z))
A nested pattern is a pattern that contains other non-trivial patterns (where by "non-trivial" I mean "not a variable or wildcard pattern").
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.
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.
This means that you can match against a pattern that contains another pattern. In your example, the (x, y)
pattern is contained inside the larger ((x, y), z)
pattern. The nesting can be arbitrarily deep, e.g. all of the following are legal:
f ((x2,x0),x1) = ()
f' (((x3, x2),x0),x1) = ()
f'' ((((x4,x3), x2),x0),x1) = ()
f''' (((((x5,x4),x3), x2),x0),x1) = ()
and so on. This also extends to lists and algebraic datatypes:
f [[x]] = ()
f' [[[x]]] = ()
g (Just (Just x)) = ()
g' (Just (Just (Just x))) = ()
Here, f
takes a list of lists, f'
takes a list of lists of lists, g
takes a Maybe
that contains another Maybe
(that is, Maybe (Maybe a)
), and g'
takes a Maybe (Maybe (Maybe a))
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