Monday, 3 January 2011

Patterns are everywhere!

When people first learn languages from the ML family, like F#, they often mistakenly assume that patterns appear only in match or function expressions. In fact, patterns also appear on the left-hand-side of let-bound definitions. This is why you can write:

let f(a, b) = a + b

The pattern is used to destructure a tuple. Specifically, a pair. But this is not just restricted to tuples. You can use that pattern to destructure much more. For example, the following destructures a pair of pairs:

let f((x1, y1), (x2, y2)) = x1 + x2, y1 + y2

Things start to get interesting when you pull in some of the more advanced pattern matching features in F#. For example, the following uses an or-pattern to select the value x is bound to depending upon the structure of the input:

let def (_, Some x | x, None) = x

This function takes a pair of values. The second value is of an option type. If that second value has the structure Some then its argument is the return value of the def function. Otherwise, the structure is None and the first argument is returned. Therefore, this def function mimics the behaviour of the built-in defaultArg function, returning the value conveyed by an optional type (if any) or a given default value otherwise.

Pattern matching is one of the enormously powerful features offered by the F# programming language. This feature and more are described in my new book Visual F# 2010 for Technical Computing.


1 comment:

Arlen said...

Thanks! As I read this I thought, "nothing new, nothing new, destructuring in let arguments ..." - then I saw the pipe in the argument list. Tried it in my ML of choice (OCaml), and voilĂ ! It worked.