Tin

Examples · 29 of 339

29-iterators

for over your own types.

examples/29-iterators.tintin run examples/29-iterators.tin
// for over your own types.
//
// An iterator has `next`: it changes itself and gives Some(item), then None.
// A collection has `iter`: it gives something for to walk (an array, a Map, a Set or an iterator).

/// Joint angles from a recorded trajectory, one sample per tick, at most `limit` samples.
type Samples = { data: float[], at: int, limit: int }

fn Samples.next(s: inout Samples): Option<float> {
  if s.at >= s.data.len || s.at >= s.limit { return None }
  s.at += 1
  Some(s.data[s.at - 1])
}

/// The Collatz sequence from n down to 1: an iterator with no array behind it.
type Collatz = { n: int, done: bool }

fn Collatz.next(c: inout Collatz): Option<int> {
  if c.done { return None }
  let v = c.n
  if v == 1 { c.done = true } else if v % 2 == 0 { c.n = v / 2 } else { c.n = 3 * v + 1 }
  Some(v)
}

/// A fleet is a collection: `for robot in fleet` walks its robots by name.
type Fleet = { robots: Map<string, float> }

fn Fleet.iter(f: Fleet): Map<string, float> => f.robots

fn main() {
  let traj = Samples { data: [0.1, 0.4, 0.9, 1.2, 1.4], at: 0, limit: 3 }
  for i, a in traj { print("tick {i}: {a} rad") }

  var steps: int[] = []
  for v in (Collatz { n: 6, done: false }) { steps.push(v) }
  print(steps)

  let fleet = Fleet { robots: mapOf([("arm", 0.92), ("rover", 0.41)]) }
  for name, battery in fleet {
    let state = if battery < 0.5 { "charge" } else { "ok" }
    print("{name}: {state}")
  }
}
tick 0: 0.1 rad
tick 1: 0.4 rad
tick 2: 0.9 rad
[6, 3, 10, 5, 16, 8, 4, 2, 1]
arm: ok
rover: charge