You will use
pooka/list:list.fold(values, initial, step)pooka/float:float.min,float.max,float.to_string- A class to carry several running values at once
The whole program
module main
import pooka/float
import pooka/int
import pooka/io
import pooka/list
class Summary(count: Int, total: Float, lowest: Float, highest: Float)
summarise(readings: List(Float)) -> Option(Summary) {
match readings {
[] -> None
[first, ..] -> Some(list.fold(
readings,
Summary(0, 0.0, first, first),
fn(s: Summary, reading: Float) {
Summary(
s.count + 1,
s.total + reading,
float.min(s.lowest, reading),
float.max(s.highest, reading)
)
}
))
}
}
main() {
let night = [11.5, 9.0, 7.25, 6.5, 8.75]
match summarise(night) {
Some(s) -> {
io.println("readings: " + int.to_string(s.count))
io.println("coldest: " + float.to_string(s.lowest))
io.println("warmest: " + float.to_string(s.highest))
io.println("average: " + float.to_string(s.total / s.count))
Nil
}
None -> {
io.println("No readings tonight.")
Nil
}
}
}
Run it
$ pooka run
readings: 5
coldest: 6.5
warmest: 11.5
average: 8.6
How it works
- A fold carries a value along. It starts with
initialand callsstep(carried, item)for each item. Whateverstepreturns is carried to the next item. - Carry a class, not a number.
Summaryholds the count, the total, the lowest and the highest, so one walk through the list fills in all four. - An empty list has no coldest night.
summarisereturnsOption(Summary):Nonefor no readings, andSomeotherwise. The first reading starts both the lowest and the highest. /gives aFloat.s.total / s.countmixes aFloatand anInt, and the answer is always aFloat, here8.6.
Try next: list.reduce folds without a starting value and returns None for an empty list. list.fold_until stops early when the answer is already known.