Pattern Matching
Pattern matching may be seen as a more sophisticated alternative to both if-then-else, and case statements. It is available in many programming languages with functional programming features, such as ML and many others. Here is a simple example written in the OCaml language:
match fruit with | "apple" -> cook pie | "coconut" -> cook dango_mochi | "banana" -> mix;;The power of pattern matching is the ability to concisely match not only actions but also values to patterns of data. Here is an example written in Haskell which illustrates both of these features:
map _ = map f (h : t) = f h : map f tThis code defines a function map, which applies the first argument (a function) to each of the elements of the second argument (a list), and returns the resulting list. The two lines are the two definitions of the function for the two kinds of arguments possible in this case – one where the list is empty (just return an empty list) and the other case where the list is not empty.
Pattern matching is not strictly speaking always a choice construct, because it is possible in Haskell to write only one alternative, which is guaranteed to always be matched – in this situation, it is not being used as a choice construct, but simply as a way to bind names to values. However, it is frequently used as a choice construct in the languages in which it is available.
Read more about this topic: Conditional (computer Programming)
Famous quotes containing the word pattern:
“A two-week-old infant cries an average of one and a half hours every day. This increases to approximately three hours per day when the child is about six weeks old. By the time children are twelve weeks old, their daily crying has decreased dramatically and averages less than one hour. This same basic pattern of crying is present among children from a wide range of cultures throughout the world. It appears to be wired into the nervous system of our species.”
—Lawrence Kutner (20th century)