Conditional (computer Programming) - Pattern Matching

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 t

This 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:

    His talent was as natural as the pattern that was made by the dust on a butterfly’s wings. At one time he understood it no more than the butterfly did and he did not know when it was brushed or marred. Later he became conscious of his damaged wings and of their construction and he learned to think and could not fly any more because the love of flight was gone and he could only remember when it had been effortless.
    Ernest Hemingway (1899–1961)