typestar

The List module in F#

map, filter, sortBy, sumBy: the daily toolkit.

// The List module is the daily toolkit: map, filter, sortBy, sum.
let harvestsKg = [("Willow", 14.2); ("Bramble", 8.9); ("Clover", 18.4)]

harvestsKg
|> List.sortByDescending snd
|> List.iter (fun (hive, kg) -> printfn "%-8s %5.1f kg" hive kg)

let totalKg = harvestsKg |> List.sumBy snd
printfn "Season total: %.1f kg" totalKg

let goodYears =
    harvestsKg |> List.filter (fun (_, kg) -> kg > 10.0)
               |> List.map fst
printfn "Above ten kilos: %A" goodYears

How it works

  1. sortByDescending snd orders pairs by their second slot.
  2. sumBy snd folds one field of every tuple.
  3. filter then map extracts the good years' names.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
454
Tokens
111
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 102 seconds.

Type this snippet

Step 2 of 3 in Lists, step 11 of 27 in Language basics.

← Previous Next →

The List module in other languages