← Cookbook Collections Intermediate · Pooka 0.5.0

Fold a list into a summary

Walk a list once and come back with everything you wanted to know about it, carried in a small class.

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

src/main.pooka
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

  1. A fold carries a value along. It starts with initial and calls step(carried, item) for each item. Whatever step returns is carried to the next item.
  2. Carry a class, not a number. Summary holds the count, the total, the lowest and the highest, so one walk through the list fills in all four.
  3. An empty list has no coldest night. summarise returns Option(Summary): None for no readings, and Some otherwise. The first reading starts both the lowest and the highest.
  4. / gives a Float. s.total / s.count mixes a Float and an Int, and the answer is always a Float, here 8.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.