Switch in F#

Here’s the full translation of the provided code into F# along with the explanation:


Switch statements express conditionals across many branches.

Here’s a basic switch.

open System

[<EntryPoint>]
let main argv = 
    let i = 2
    printf "Write %d as " i
    match i with
    | 1 -> printfn "one"
    | 2 -> printfn "two"
    | 3 -> printfn "three"
    | _ -> ()

    // You can use commas to separate multiple expressions in the same case statement. 
    // We use the optional default case in this example as well.
    match DateTime.Now.DayOfWeek with
    | DayOfWeek.Saturday | DayOfWeek.Sunday -> printfn "It's the weekend"
    | _ -> printfn "It's a weekday"

    // switch without an expression is an alternate way to express if/else logic.
    // Here we also show how the case expressions can be non-constants.
    let t = DateTime.Now
    match t.Hour < 12 with
    | true -> printfn "It's before noon"
    | false -> printfn "It's after noon"

    // A type switch compares types instead of values.
    // You can use this to discover the type of an interface value.
    let whatAmI (i: obj) =
        match i with
        | :? bool -> printfn "I'm a bool"
        | :? int -> printfn "I'm an int"
        | _ -> printfn "Don't know type %A" i

    whatAmI (box true)
    whatAmI (box 1)
    whatAmI (box "hey")

    0

To execute this F# code, put it into a file named SwitchExample.fs and use the dotnet CLI to run it.

$ dotnet fsi SwitchExample.fs

You should see the following output:

Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type "hey"

This demonstrates how switch statements and pattern matching work in F#. Now that we can run and interpret basic F# programs, let’s learn more about the language.

Next example: Arrays.