temp_stats.ml in OCaml
A week of temperatures: fold-picked extremes, a bar chart, swings.
(* Summarize a week of temperature readings: extremes, mean, swings. *)
let readings = [
("Mon", -4.0); ("Tue", -1.5); ("Wed", 2.0); ("Thu", 3.5);
("Fri", 1.0); ("Sat", -2.5); ("Sun", -6.0);
]
let () =
let temps = List.map snd readings in
let coldest =
List.fold_left (fun a b -> if snd b < snd a then b else a)
(List.hd readings) readings in
let warmest =
List.fold_left (fun a b -> if snd b > snd a then b else a)
(List.hd readings) readings in
Printf.printf "Coldest: %s at %.1f C\n" (fst coldest) (snd coldest);
Printf.printf "Warmest: %s at %.1f C\n" (fst warmest) (snd warmest);
let mean =
List.fold_left ( +. ) 0.0 temps
/. float_of_int (List.length temps) in
Printf.printf "Mean: %.1f C\n" mean;
(* Chart each day against the freezing line. *)
readings
|> List.iter (fun (day, t) ->
let len = max 1 (int_of_float (t +. 7.0)) in
let side = if t > 0.0 then "above" else "below" in
Printf.printf "%-4s %5.1f %s %s\n" day t (String.make len '#')
side);
(* Pair each temp with its successor for the overnight swings. *)
let swings =
List.map2 (fun a b -> abs_float (b -. a))
(List.filteri (fun i _ -> i < List.length temps - 1) temps)
(List.tl temps)
in
Printf.printf "Sharpest overnight swing: %.1f C\n"
(List.fold_left max 0.0 swings)
How it works
- Folds with a comparator find the coldest and warmest days.
- The chart loop destructures each pair and prints columns.
List.map2over the list and its tail pairs the overnights.
Keywords and builtins used here
elsefunifinletthen
The run, in numbers
- Lines
- 39
- Characters to type
- 1244
- Tokens
- 354
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 354 seconds.
Step 3 of 3 in Encore, step 29 of 29 in Language basics.