You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Pattern Matching

All programs need to sift and sort through data; to do this in functional programming, you use pattern matching. Pattern matching is similar to a switch statement from C# or C++, but it is much more powerful. A pattern match is a series of rules that will execute if the pattern matches the input. The pattern-match expression then returns the result of the rule that was matched; therefore, all rules in a pattern match must return the same type.

To do pattern matching, you use the match and with keywords with a series of pattern rules, each followed by an arrow, ->. The following snippet shows using a pattern matching against the expression isOdd x to mimic the behavior of an if expression. The first rule matches the true value, and if that rule matches, it will print "x is odd" to the console:

> // Simple pattern matching
let isOdd x = (x % 2 = 1)

let describeNumber x =
    match isOdd x with
    | true  -> printfn "x is odd"
    | false -> printfn "x is even";;

val isOdd : int -> bool
val describeNumber : int -> unit

> describeNumber 4;;
x is even
val it : unit = ()

The simplest sort of pattern matching is against constant values. Example 3-5 constructs a truth table for the Boolean function And by matching both values of a tuple simultaneously.

Example 3-5. Constructing a truth table using pattern matching

> // Truth table for AND via pattern matching let testAnd x y = match x, y with | true, true -> true | true, false -> false | false, true -> false | false, false -> false;; val ...

The best content for your career. Discover unlimited learning on demand for around $1/day.