Pattern Matching - Primitive Patterns

Primitive Patterns

The simplest pattern in pattern matching is an explicit value or a variable. For an example, consider a simple function definition in Haskell syntax (function parameters are not in parentheses but are separated by spaces, = is not assignment but definition):

f 0 = 1

Here, 0 is a single value pattern. Now, whenever f is given 0 as argument the pattern matches and the function returns 1. With any other argument, the matching and thus the function fail. As the syntax supports alternative patterns in function definitions, we can continue the definition extending it to take more generic arguments:

f n = n * f (n-1)

Here, the first n is a single variable pattern, which will match absolutely any argument and bind it to name n to be used in the rest of the definition. In Haskell (unlike at least Hope), patterns are tried in order so the first definition still applies in the very specific case of the input being 0, while for any other argument the function returns n * f (n-1) with n being the argument.

The wildcard pattern (often written as _) is also simple: like a variable name, it matches any value, but does not bind the value to any name.

Read more about this topic:  Pattern Matching

Famous quotes containing the words primitive and/or patterns:

    Every modern male has, lying at the bottom of his psyche, a large, primitive being covered with hair down to his feet. Making contact with this Wild Man is the step the Eighties male or the Nineties male has yet to take. That bucketing-out process has yet to begin in our contemporary culture.
    Robert Bly (b. 1926)

    Phenomenal nature shadows him wherever he goes. Clouds in the staring sky transmit to one another, by means of slow signs, incredibly detailed information regarding him. His inmost thoughts are discussed at nightfall, in manual alphabet, by darkly gesticulating trees. Pebbles or stains or sunflecks form patterns representing in some awful way messages which he must intercept. Everything is a cipher and of everything he is the theme.
    Vladimir Nabokov (1899–1977)