Educating about C# and F#

Seq.choose - F#

Lets examine Seq.choose.

Seq.choose: Applies the given function to each element of the list. Return the list comprised of the results “x” for each element where the function returns Some(x). ~ FSharp.Core

In imperative languages where you might return null, F# leverages the Option type.

type Option<'a> =
    | Some of 'a
    | None

A result either exists (Some of ‘a) or it doesn’t exist (None). This is quiet common, and so Seq.choose supports filtering and upwraping of Option types.

let main argv =    
    let ids = 
        [Some 1; None; Some 2] 
        |> Seq.choose id

    printfn "%A" ids

Our input sequence has 3 values, 2 of Some, 1 of None. Our Seq.choose filters out the None and the output of this example is seq [1; 2].

The id function above is called the identity function. It returns whatever is passed to it. So in this case the function didn’t generate Some/None values, but just passed through already generated Some/None values from the input sequence. This stackoverflow has a great explanation.