.nib std
nib 0.3.0

module use "std/iter.nib"

Iter

Lazy walks over a sequence: build one from a Vec, a range or an endless producer, transform it element by element, and stop as early as the answer allows.

An Iter.Iter<'t> is a sequence you have not walked yet. Building one does no work per element, and transforming it with Iter.map or Iter.filter answers a new walk without walking the old one. The elements are produced only when a terminal — Iter.to_vec, Iter.take, Iter.run — asks for them, and a terminal that has its answer stops asking. That is what lets a walk be endless.

let evens = Iter.filter(Iter.naturals(1)) { x -> x % 2 == 0 };
let squares = Iter.map(evens) { x -> x * x };
Iter.take(squares, 4)
#[4, 16, 36, 64]

Reach for Iter when a Vec cannot answer directly: a walk that should stop early, a source with no end or no Vec behind it, or several steps in one pass. For a Vec you already hold and want transformed whole, Vec.map and Vec.filter are simpler.

An Iter is a value, not a cursor: walking it neither consumes nor changes it, so the same walk can be handed to two terminals and each sees every element.

let i = Iter.of_vec(#[10, 20, 30]);
(Iter.to_vec(i), Iter.run(i, 0) { acc, x -> acc + x })
(#[10, 20, 30], 60)

Producers

A walk comes from Iter.of_vec (an existing Vec), Iter.range (a half-open run of integers), Iter.naturals and Iter.repeat (endless), Iter.empty, or Iter.of_stepper for a walk you write yourself. A type that can hand out its elements implements the Iter.Iterable interface.

Transformers

A stepper takes a walk and answers a walk: Iter.map, Iter.filter, Iter.zip_with and Iter.concat. They are lazy — each element is transformed when a terminal pulls it — so they work on endless walks. Nest them freely; the innermost call is the source.

Terminals

A terminal walks and answers a value. Iter.to_vec collects everything, Iter.take collects the first n and stops. For any other question, Iter.run threads an accumulator of your choosing through the walk: a count, a sum, a record. There is no count or sum built in because each is one run.

A step can end the walk early by raising FoldStopped(acc) — "the answer is this accumulator". Iter.run catches it and answers acc; Iter.reduce lets it out to the caller.

Iter.run(Iter.naturals(1), 0) { acc, x -> if acc + x > 20 then raise FoldStopped(acc) else acc + x }
15

To stop with a single element rather than an accumulator — "the first one that matches" — raise FoldFound(x) from a Iter.FoundStep and drive it with Iter.run_found.

Lenses

A lens is a transformation not yet attached to anything: Iter.Lens.map, Iter.Lens.filter, Iter.Lens.flat_map and Iter.Lens.take_while each answer an Iter.Lens.Lens, and Iter.Lens.chain joins two. A lens is a value, so it can be named, stored and reused. Iter.collect runs one over a Vec in a single call:

let lens = Iter.Lens.chain(Iter.Lens.filter { x -> x % 2 == 0 }, Iter.Lens.map { x -> x * 10 });
Iter.collect(#[1, 2, 3, 4, 5, 6], lens, #[], Iter.to_vec)
#[20, 40, 60]

Steppers are lazy and work on endless walks; lenses run eagerly over the whole input. Prefer the steppers unless you want a transformation as a value.

Data

data FoldStopped<'acc> where
  FoldStopped('acc)

The signal a step raises to end a walk early, carrying the accumulator the walk should answer. Iter.run and Iter.take catch it; Iter.reduce lets it out, so a caller of reduce either rescues it or declares raises FoldStopped.

try Iter.reduce(Iter.naturals(0), 0) { acc, x -> if x > 4 then raise FoldStopped(acc) else acc + x }
rescue FoldStopped(total) => total end
10
data FoldFound<'t> where
  FoldFound('t)

The signal a Iter.FoundStep raises to end a walk with one element as the answer. Iter.run_found lets it out for the caller to rescue.

try Iter.run_found(Iter.naturals(1), 0, Iter.found_step { acc, x -> if x * x > 50 then raise FoldFound(x) else acc })
rescue FoldFound(x) => x end
8
dataStep
data Step<'acc, 't> where
  run :: pin (('acc, 't) -> 'acc raises FoldStopped)

A step held as a value: one function run(acc, x) that answers the next accumulator and may raise FoldStopped. Build one with Iter.step or the literal Iter.Step { run: … }, and drive it with Iter.run_step or Iter.reduce_step. A lens is attached to a walk by applying it to a Step.

let sum = Iter.Step { run: { acc, x -> acc + x } };
Iter.run_step(Iter.range(1, 5), 0, sum)
10
data FoundStep<'acc, 't> where
  run :: pin (('acc, 't) -> 'acc raises FoldStopped, FoldFound)

Like Iter.Step, but run may also raise FoldFound. Build one with Iter.found_step and drive it with Iter.run_found or Iter.reduce_found. The plain drivers refuse a FoundStep at compile time, so a FoldFound cannot escape a caller that never declared it.

let first_long = Iter.found_step { acc, w -> if String.length(w) > 3 then raise FoldFound(w) else acc };
try Iter.run_found(Iter.of_vec(#["a", "bee", "cicada", "dragonfly"]), "", first_long)
rescue FoldFound(w) => w end
cicada
dataMove
data Move<'t> where
  Done;
  Next('t, Iter<'t>)

What one step of a walk answers: Iter.Done when the walk is over, or Iter.Next(item, rest), where rest is the walk of everything after item. You meet it when writing a producer with Iter.of_stepper, or when taking a walk apart by hand.

let describe = { i ->
  match i.step()
    Done => "empty"
    Next(x, rest) => "starts with {x}"
  end };
(describe(Iter.of_vec(#[7, 8])), describe(Iter.range(3, 3)))
("starts with 7", "empty")
dataIter
data Iter<'t> where
  step :: pin () -> Move<'t>

A walk: a record with one field, step, answering an Iter.Move. Asking the same Iter for its step twice gives the same answer, so an Iter can be walked any number of times, stored in a record, or handed on. Endless walks are fine as long as the terminal stops.

let three = Iter.of_vec(#[1, 2, 3]);
(Iter.to_vec(three), Iter.to_vec(three), Iter.take(Iter.repeat("x"), 2))
(#[1, 2, 3], #[1, 2, 3], #["x", "x"])
dataTally
data Tally<'t> where
  seen :: Int;
  kept :: Vec<'t>

A ready-made accumulator for "how many did I see, and which did I keep": seen counts, kept collects. Use it with Iter.run, or copy its shape when your question is different.

Iter.run(Iter.of_vec(#[1, 2, 3, 4]), Iter.Tally { seen: 0, kept: #[] }) { t, x ->
  if x % 2 == 0 then Iter.Tally { seen: t.seen + 1, kept: Vec.push(t.kept, x) }
  else Iter.Tally { seen: t.seen + 1, kept: t.kept } }
#{seen: 4, kept: #[2, 4]}
data Lens<'acc, 'a, 'b> where
  apply :: pin (Step<'acc, 'b>) -> Step<'acc, 'a>

A transformation with its downstream end still open, written Iter.Lens.Lens<'acc, 'a, 'b>: it takes 'as in and hands 'bs on to whatever Iter.Step it is applied to. lens.apply(step) answers a new Step that runs the transformation and then step; Iter.collect does that for you over a Vec. Build lenses with the functions below rather than by hand.

A lens bound with let is fixed to one accumulator type by its first use; to stand the same transformation on a Vec and on an Int, build it twice.

let doubled = Iter.Lens.map { x -> x * 2 };
let into_vec = doubled.apply(Iter.push());
let into_sum = Iter.Lens.map({ x -> x * 2 }).apply(Iter.step { acc, x -> acc + x });
(Iter.run_step(Iter.range(1, 4), #[], into_vec), Iter.run_step(Iter.range(1, 4), 0, into_sum))
(#[2, 4, 6], 12)

Interfaces

interfaceIterable
interface Iterable<'t> where
  iter() -> Iter<'t>

The producer protocol: anything that can hand out its elements as a walk. Implement it with an effector whose iter() answers an Iter.Iter<'t>, bind it in a wire, and call @Iter.Iterable.iter() — or take it as a parameter of type Iter.Iterable<'t> and call e.iter(). Each call answers a fresh walk, so a function can read the same producer twice.

use "std/iter.nib"

effector Letters is Iter.Iterable where
  iter() = Iter.of_vec(#["a", "b", "c"])

module Example where
  func count :: e: Iter.Iterable<'t> -> Int =
    Iter.run(e.iter(), 0) { acc, x -> acc + 1 }

  func main() =
    (Example.count(Iter.Iterable), Iter.to_vec(@Iter.Iterable.iter()))

wire W runs Example.main where Iter.Iterable = Example.Letters
(3, #["a", "b", "c"])

Functions

func id :: -> Lens<'acc, 't, 't>

The lens that changes nothing. Useful where a lens is a parameter and the caller wants no transformation, or as the starting point of a chain.

Iter.collect(#[1, 2, 3], Iter.Lens.id(), #[], Iter.to_vec)
#[1, 2, 3]
func map :: f: pin ('a) -> 'b -> Lens<'acc, 'a, 'b>

A lens that applies f to each element on the way through. The lens counterpart of Iter.map.

Iter.collect(#["a", "bb", "ccc"], Iter.Lens.map { s -> String.length(s) }, #[], Iter.to_vec)
#[1, 2, 3]
func filter :: p: pin ('a) -> Bool -> Lens<'acc, 'a, 'a>

A lens that passes on only the elements for which p answers true. The lens counterpart of Iter.filter.

Iter.collect(#[1, 2, 3, 4, 5], Iter.Lens.filter { x -> x % 2 == 1 }, #[], Iter.to_vec)
#[1, 3, 5]
func flat_map :: f: pin ('a) -> Vec<'b> -> Lens<'acc, 'a, 'b>

A lens that turns each element into a Vec and passes on its elements in order.

Iter.collect(#[1, 2, 3], Iter.Lens.flat_map { x -> #[x, x * 10] }, #[], Iter.to_vec)
#[1, 10, 2, 20, 3, 30]
func take_while :: p: pin ('a) -> Bool -> Lens<'acc, 'a, 'a> raises FoldStopped

A lens that passes elements on while p answers true and stops the whole walk at the first one it refuses; later elements are never looked at. It is the one lens that raises FoldStopped, and the function that builds it must declare raises FoldStopped even when the driver catches the stop.

Iter.collect(#[1, 2, 3, 1, 2], Iter.Lens.take_while { x -> x < 3 }, #[], Iter.to_vec)
#[1, 2]
func chain :: first: Lens<'acc, 'b, 'a>, next: Lens<'acc, 'c, 'b> -> Lens<'acc, 'c, 'a>

Joins two lenses: elements meet first, then next, so each stage sees what the one before it passed on. For three stages, nest: chain(a, chain(b, c)).

let keep_then_map = Iter.Lens.chain(Iter.Lens.filter { x -> x > 1 }, Iter.Lens.map { x -> x * 100 });
let map_then_keep = Iter.Lens.chain(Iter.Lens.map { x -> x * 100 }, Iter.Lens.filter { x -> x > 150 });
(Iter.collect(#[1, 2, 3], keep_then_map, #[], Iter.to_vec), Iter.collect(#[1, 2, 3], map_then_keep, #[], Iter.to_vec))
(#[200, 300], #[200, 300])
funcstep
func step :: run: pin (('acc, 't) -> 'acc raises FoldStopped) -> Step<'acc, 't>

Wraps a function (acc, x) -> acc as an Iter.Step, for Iter.run_step, Iter.reduce_step, or applying a lens. The function may raise FoldStopped to end the walk.

Iter.run_step(Iter.of_vec(#["n", "i", "b"]), "", Iter.step { acc, s -> acc ++ s })
nib
func found_step :: run: pin (('acc, 't) -> 'acc raises FoldStopped, FoldFound) -> FoundStep<'acc, 't>

Wraps a function as an Iter.FoundStep: like Iter.step, but the function may also raise FoldFound(x) to end the walk with an element as the answer.

let at_least = Iter.found_step { acc, x -> if x >= 10 then raise FoldFound(x) else acc };
try Iter.run_found(Iter.of_vec(#[3, 8, 12, 20]), 0, at_least) rescue FoldFound(x) => x end
12
funcpush
func push :: -> Step<Vec<'t>, 't>

The Iter.Step that appends each element to a Vec accumulator. Apply a lens to it to collect what the lens passes on.

Iter.run_step(Iter.range(0, 4), #[], Iter.push())
#[0, 1, 2, 3]
funcreduce
func reduce :: i: Iter<'t>, init: 'acc, step: (('acc, 't) -> 'acc raises FoldStopped) -> 'acc raises FoldStopped

Walks i in order, calling step(acc, x) for each element starting from init, and answers the final accumulator. A FoldStopped raised by step is not caught: it leaves reduce, so the caller rescues it or declares it. Use Iter.run when you just want the stopped accumulator back.

Iter.reduce(Iter.range(1, 6), 1) { acc, x -> acc * x }
120
func reduce_step :: i: Iter<'t>, init: 'acc, step: Step<'acc, 't> -> 'acc raises FoldStopped

Iter.reduce for a step held as an Iter.Step value.

let lens = Iter.Lens.take_while { x -> x < 3 };
try Iter.reduce_step(Iter.of_vec(#[1, 2, 3, 4]), 0, lens.apply(Iter.step { acc, x -> acc + x }))
rescue FoldStopped(acc) => acc end
3
funcrun
func run :: i: Iter<'t>, init: 'acc, step: (('acc, 't) -> 'acc raises FoldStopped) -> 'acc

Walks i, threading an accumulator through step from init, and answers where it ended. If step raises FoldStopped(acc), the walk stops and run answers acc, so run itself never raises. This is the general-purpose terminal: count, sum, search, or build any accumulator you like.

let words = Iter.of_vec(#["ox", "nib", "lamb", "yak"]);
let longest = Iter.run(words, "") { best, w -> if String.length(w) > String.length(best) then w else best };
let first_three_letter = Iter.run(words, "") { acc, w -> if String.length(w) == 3 then raise FoldStopped(w) else acc };
(longest, first_three_letter)
("lamb", "nib")
func run_step :: i: Iter<'t>, init: 'acc, step: Step<'acc, 't> -> 'acc

Iter.run for a step held as an Iter.Step value — the usual way to drive a lens applied to a step.

let lens = Iter.Lens.map { x -> x * x };
Iter.run_step(Iter.range(1, 5), 0, lens.apply(Iter.step { acc, x -> acc + x }))
30
func reduce_found :: i: Iter<'t>, init: 'acc, step: FoundStep<'acc, 't> -> 'acc raises FoldStopped, FoldFound

Walks i with an Iter.FoundStep, letting both FoldStopped and FoldFound out to the caller. Below, a found element is answered negated so the two outcomes are told apart.

let s = Iter.found_step { acc, x -> if x == 3 then raise FoldFound(x) else acc + x };
try Iter.reduce_found(Iter.of_vec(#[1, 2, 3, 4]), 0, s)
rescue FoldFound(x) => -x
rescue FoldStopped(acc) => acc end
-3
func run_found :: i: Iter<'t>, init: 'acc, step: FoundStep<'acc, 't> -> 'acc raises FoldFound

Walks i with an Iter.FoundStep. A FoldStopped(acc) answers acc, as in Iter.run; a FoldFound(x) leaves run_found for the caller to rescue. If nothing is found, the answer is the final accumulator.

let first_neg = Iter.found_step { acc, x -> if x < 0 then raise FoldFound(x) else acc + 1 };
let look = { v -> try Iter.run_found(Iter.of_vec(v), 0, first_neg) rescue FoldFound(x) => x end };
(look(#[4, -2, 7]), look(#[1, 2]))
(-2, 2)
functo_vec
func to_vec :: i: Iter<'t> -> Vec<'t>

Every element of the walk, in order, in a new Vec. An empty walk answers #[]. It reads until the walk ends, so do not hand it an endless walk — use Iter.take.

(Iter.to_vec(Iter.range(0, 5)), Iter.to_vec(Iter.empty()))
(#[0, 1, 2, 3, 4], #[])
functake
func take :: i: Iter<'t>, n: Int -> Vec<'t>

The first n elements, or all of them if there are fewer. Stops as soon as it has n, so it is safe on an endless walk. n of 0 or less answers #[] without walking at all.

(Iter.take(Iter.naturals(100), 3), Iter.take(Iter.of_vec(#[1, 2]), 10), Iter.take(Iter.naturals(0), 0))
(#[100, 101, 102], #[1, 2], #[])
funcempty
func empty :: -> Iter<'t>

The walk with no elements.

let none: Iter.Iter<Int> = Iter.empty();
(Iter.to_vec(none), Iter.run(none, 0) { acc, x -> acc + 1 })
(#[], 0)
funcof_vec
func of_vec :: v: Vec<'t> -> Iter<'t>

A walk over the elements of v, in order. The Vec is not copied.

Iter.to_vec(Iter.map(Iter.of_vec(#["a", "b"])) { s -> s ++ s })
#["aa", "bb"]
funcrange
func range :: lo: Int, hi: Int -> Iter<Int>

The integers from lo up to, but not including, hi. When lo is not less than hi the walk is empty; it never raises. Nothing is stored, so a large range costs nothing until it is walked.

(Iter.to_vec(Iter.range(2, 6)), Iter.to_vec(Iter.range(5, 5)), Iter.take(Iter.range(0, 1000000), 3))
(#[2, 3, 4, 5], #[], #[0, 1, 2])
func naturals :: from: Int -> Iter<Int>

from, from + 1, from + 2, … with no end. Drive it only with a terminal that stops — Iter.take, or Iter.run with a step that raises FoldStopped.

Iter.take(Iter.naturals(10), 4)
#[10, 11, 12, 13]
funcrepeat
func repeat :: x: 't -> Iter<'t>

x, forever. Like Iter.naturals, it needs a terminal that stops.

Iter.to_vec(Iter.zip_with(Iter.of_vec(#["a", "b", "c"]), Iter.repeat("!")) { s, bang -> s ++ bang })
#["a!", "b!", "c!"]
func of_stepper :: k: pin () -> Move<'t> -> Iter<'t>

A walk whose step is the function k: each call answers Iter.Next(item, rest) or Iter.Done. This is how to write a producer that of_vec and range do not cover.

let one_two = Iter.of_stepper { -> Iter.Next(1, Iter.of_stepper { -> Iter.Next(2, Iter.empty()) }) };
Iter.to_vec(one_two)
#[1, 2]
func of_source :: p: pin (Step<Vec<'t>, 't>) -> Vec<'t> -> Iter<'t>

A walk over the items a driving producer hands out. p is given a sink Iter.Step; it calls sink.run(acc, item) once per item, threading the accumulator from #[], and answers the final Vec. Every item is collected before the walk starts, so the producer must finish.

let src = Iter.of_source { sink -> Vec.fold(#["x", "y"], #[]) { acc, s -> sink.run(acc, s) } };
Iter.to_vec(src)
#["x", "y"]
funcmap
func map :: i: Iter<'t>, f: pin ('t) -> 'u -> Iter<'u>

A walk of f applied to each element of i. Lazy: f runs when a terminal pulls the element, so it works on endless walks.

Iter.take(Iter.map(Iter.naturals(1)) { x -> x * x }, 5)
#[1, 4, 9, 16, 25]
funcfilter
func filter :: i: Iter<'t>, keep: pin ('t) -> Bool -> Iter<'t>

A walk of the elements of i for which keep answers true, in order. Lazy, like Iter.map.

Iter.take(Iter.filter(Iter.naturals(1)) { x -> x % 7 == 0 }, 3)
#[7, 14, 21]
func zip_with :: a: Iter<'t>, b: Iter<'u>, f: pin ('t, 'u) -> 'v -> Iter<'v>

Walks a and b together, answering f(x, y) for each pair. Ends when either side ends, so the result is as long as the shorter walk.

Iter.to_vec(Iter.zip_with(Iter.of_vec(#["ada", "bo", "cy"]), Iter.naturals(1)) { name, n -> #{ rank: n, name: name } })
#[#{rank: 1, name: "ada"}, #{rank: 2, name: "bo"}, #{rank: 3, name: "cy"}]
func through :: i: Iter<'t>, lens: Iter.Lens.Lens<Vec<'u>, 't, 'u> -> Iter<'u>

Runs a lens over a walk and answers a walk of what came out. Unlike the steppers, it walks all of i before answering, so it cannot be used on an endless walk; prefer Iter.map and Iter.filter when they will do.

let lens = Iter.Lens.flat_map { x -> #[x, x] };
Iter.to_vec(Iter.through(Iter.range(1, 4), lens))
#[1, 1, 2, 2, 3, 3]
funcconcat
func concat :: a: Iter<'t>, b: Iter<'t> -> Iter<'t>

The elements of a, then the elements of b. b is not touched until a is finished, so if a is endless b never contributes.

(Iter.to_vec(Iter.concat(Iter.range(0, 2), Iter.of_vec(#[10, 11]))), Iter.take(Iter.concat(Iter.naturals(0), Iter.repeat(-1)), 3))
(#[0, 1, 10, 11], #[0, 1, 2])
func collect :: v: Vec<'a>, lens: Iter.Lens.Lens<'acc, 'a, 'b>, init: 'acc, terminal: pin (Iter<'b>) -> 'r -> 'r

Runs lens over the elements of v and hands the result, as a walk, to terminal — one call for "this Vec, through this lens, into this answer". init is the starting Vec the lens collects into, usually #[]. terminal is a function taking one walk, such as Iter.to_vec. The lens runs over all of v before the terminal starts, and a FoldStopped from the lens ends that run early.

let shout = Iter.Lens.chain(Iter.Lens.filter { s -> String.length(s) > 2 }, Iter.Lens.map { s -> s ++ "!" });
Iter.collect(#["hi", "hey", "hello"], shout, #[], Iter.to_vec)
#["hey!", "hello!"]

Internal helpers

These are reachable — nib has no private functions — but they are the module's own plumbing, not an interface it promises to keep.

1 signature(s)
func filter_step :: i: Iter<'t>, keep: pin ('t) -> Bool -> Move<'t>