typestar

groupBy and countBy in F#

Bucket a list by computed key, then fold each bucket.

// groupBy buckets a list by a computed key in one pass.
let harvests =
    [ "Willow", "spring", 6.2; "Willow", "summer", 8.0
      "Bramble", "spring", 4.1; "Clover", "summer", 9.3 ]

harvests
|> List.groupBy (fun (hive, _, _) -> hive)
|> List.map (fun (hive, rows) ->
    hive, rows |> List.sumBy (fun (_, _, kg) -> kg))
|> List.sortByDescending snd
|> List.iter (fun (hive, kg) -> printfn "%-8s %.1f kg" hive kg)

let bySeason = harvests |> List.countBy (fun (_, season, _) -> season)
printfn "Harvests per season: %A" bySeason

How it works

  1. List.groupBy pairs each key with its rows.
  2. A map over the groups sums the harvest per hive.
  3. countBy is the one-call tally for categorical data.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
517
Tokens
156
Three-star pace
60 tpm

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

Type this snippet

Step 2 of 3 in Collections, step 17 of 27 in Language basics.

← Previous Next →