temp_stats.ml en OCaml
Una semana de temperaturas: extremos por pliegue, barras y saltos.
(* 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)
Cómo funciona
- Pliegues con comparador hallan los días más frío y más cálido.
- El bucle del gráfico desestructura cada par e imprime columnas.
List.map2sobre la lista y su cola empareja las noches.
Palabras clave y builtins usados aquí
elsefunifinletthen
El intento, en números
- Líneas
- 39
- Caracteres a escribir
- 1244
- Tokens
- 354
- Ritmo de tres estrellas
- 60 tpm
Al ritmo de tres estrellas de 60 tokens por minuto, este intento toma unos 354 segundos.
Paso 3 de 3 en Bis; paso 29 de 29 en Fundamentos del lenguaje.