Tree Patterns
More complex patterns can be built from the primitive ones of the previous section, usually in the same way as values are built by combining other values. The difference then is that with variable and wildcard parts, a pattern doesn't build into a single value, but matches a group of values that are the combination of the concrete elements and the elements that are allowed to vary within the structure of the pattern.
A tree pattern describes a part of a tree by starting with a node and specifying some branches and nodes and leaving some unspecified with a variable or wildcard pattern. It may help to think of the abstract syntax tree of a programming language and algebraic data types.
In Haskell, the following line defines an algebraic data type Color
that has a single data constructor ColorConstructor
that wraps an integer and a string.
The constructor is a node in a tree and the integer and string are leaves in branches.
When we want to write functions to make Color
an abstract data type, we wish to write functions to interface with the data type, and thus we want to extract some data from the data type, for example, just the string or just the integer part of Color
.
If we pass a variable that is of type Color, how can we get the data out of this variable? For example, for a function to get the integer part of Color
, we can use a simple tree pattern and write:
As well:
stringPart (ColorConstructor _ theString) = theStringThe creations of these functions can be automated by Haskell's data record syntax.
Read more about this topic: Pattern Matching
Famous quotes containing the words tree and/or patterns:
“The Anglo-American can indeed cut down, and grub up all this waving forest, and make a stump speech, and vote for Buchanan on its ruins, but he cannot converse with the spirit of the tree he fells, he cannot read the poetry and mythology which retire as he advances. He ignorantly erases mythological tablets in order to print his handbills and town-meeting warrants on them.”
—Henry David Thoreau (18171862)
“Ive begun to appreciate the generational patterns that ripple out from our lives like stones dropped in water, pulsing outward even after we are gone. Although we have but one childhood, we relive it first through our childrens and then our grandchildrens eyes.”
—Anne Cassidy (20th century)