What is a nested pattern in Haskell?
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))
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))
Though I may be wrong, I can only assume from context that an "unnested" pattern would be something like addPair x = x
or addPair x y = x+y
. Your arguments I believe are a pattern. In most programming languages, this would be a simple x y
. while in this case you your argument pattern can be more complicated, e.g. (x, y)
or ((x, y), z)
.
Nesting probably means "a tuple or list" or "a nonflat tuple or list".
精彩评论