Pattern matching in F# Programming Language

19 Aug 2023 Sejal Sah 0 F# programming language

Pattern Matching in F#: Comprehensive Guide with Examples

Pattern matching is a fundamental and powerful feature in F#, a functional-first programming language developed by Microsoft. It allows you to match different patterns in data structures like lists, tuples, records, and more, and then execute corresponding code based on the matched pattern. Pattern matching simplifies complex branching logic and can lead to more concise and readable code.

In F#, pattern matching is often used with the match keyword, which has the following syntax:

fsharp
match expression with
| pattern1 -> result1
| pattern2 -> result2
| pattern3 when condition -> result3
| _ -> defaultResult

Here's a breakdown of the components:

  • expression: The value you want to match patterns against.
  • pattern: A pattern to match against the expression. Patterns can be literals, variable names, tuples, lists, records, and more.
  • ->: Separates the pattern from the corresponding code to execute.
  • result: The code to execute when the pattern is matched.

Here are some examples of pattern matching in F#:

Example 1: Matching literals

fsharp
let describeNumber x =
    match x with
    | 0 -> "Zero"
    | 1 -> "One"
    | _ -> "Other"

Example 2: Matching tuples

fsharp
let describeTuple t =
    match t with
    | (0, _) -> "First element is zero"
    | (_, 0) -> "Second element is zero"
    | (x, y) -> sprintf "Tuple contains %d and %d" x y

Example 3: Matching lists

fsharp
let rec sumList lst =
    match lst with
    | [] -> 0
    | head :: tail -> head + sumList tail

Example 4: Matching records

fsharp
type Person = { Name: string; Age: int }

let describePerson p =
    match p with
    | { Name = "Alice"; Age = age } -> sprintf "Alice, age %d" age
    | { Name = name; Age = age } -> sprintf "Person %s is %d years old" name age

Example 5: Using guards

fsharp

let describeTemperature temp =
    match temp with
    | t when t < 0 -> "Freezing"
    | t when t >= 0 && t < 20 -> "Cold"
    | t when t >= 20 && t < 30 -> "Moderate"
    | t -> "Hot"

Pattern matching in F# is a versatile and expressive feature that helps you write concise and readable code by handling different cases elegantly. It's particularly well-suited for functional programming paradigms and working with immutable data structures.

BY: Sejal Sah

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.