Match expression

Similar to a switch expression in Cβ™― 8.0 but more powerful thanks to patterns

Syntax:

match test-expression with
| pattern1 [ when condition ] -> result-expression1
| pattern2 [ when condition ] -> result-expression2
| ...

Returns the result of the 1st branch whose pattern "matches" test-expression

☝ Note: all branches must return the same type!

Exhaustivity

A C# switch must always define a default case. Otherwise: compile warning, πŸ’₯ MatchFailureException at runtime

Not necessary in a F# match expression if branches cover all cases because the compiler checks for completeness and "dead" branches

let fn x =
    match x with
    | Some true  -> "ok"
    | Some false -> "ko"
    | None       -> ""
    | _          -> "?"
//    ~  ⚠️ Warning FS0026: his rule will never be matched

☝ Tip: the more branches are exhaustive, the more code is explicit and safe

Example: checking all the cases of a union type allows you to manage the addition of a case by a warning at compile time: Warning FS0025: Special criteria incomplete in this expression

  • Detection of accidental addition

  • Identification of the code to change to handle the new case

Guard

Syntax: pattern1 when condition Usage: to refine a pattern, using constraints on variables

πŸ’‘ The guard is only evaluated if the pattern is satisfied.

Guard vs OR Pattern

The OR pattern has a higher precedence/priority than the Guard :

Pattern composition

Pattern matching is powerful not only due to its exhaustivity but also because of the pattern composition.

β†’ Example:

Notes

This example demonstrates how we match the data on 4 levels:

  1. feature is a record with the Value field (possibly amongst other fields)

  2. Value has the case Boolean of the union type FeatureValue.

  3. This union case contains an optional boolean (bool option type).

  4. We detect when the provided value is true.

Match function

Syntax:

Equivalent to a lambda taking an implicit parameter which is "matched":

Benefits:

  1. In pipelines

  1. More concise function

Limitations

Example: a function with both explicit parameters and the function keyword β†’ The number of parameters and their order can be wrong:

Exhaustivity in OOP

The equivalent of the pattern matching exhaustivity in FP is ... the Visitor design pattern in OOP

Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.

β†’ It's FP in OOP, much very convoluted.

Last updated

Was this helpful?