Skip to content

std::iter

Lazy iteration over any Iter<T>: a List, Vector, Set, Map, String, Maybe, Bytes or range, and any type with an Iter impl. Each function here is called as Iter.map(xs, f), or as a stage of a pipe:

total =
    [3, 8, 5, 12]
    |> Iter.filter(fn n -> n > 4)
    |> Iter.map(fn n -> n * 2)
    |> Iter.sum()

total is 50. No list is built between the stages: each element goes through the whole chain before the next one is read.

Import with import std::iter.

Interfaces

A List, Vector or Set yields its elements, a List and a Vector in order. A Map<K, V> yields (key, value) pairs in insertion order, a String its grapheme clusters, and a range its values. A Maybe yields its value when it is Some, so Iter.flat_map(xs, f) with an f that returns a Maybe keeps the Some values.

  • Adapters take a source and return another Iter: map, filter, reject, scan, take, drop, take_while, drop_while, flat_map, flatten, zip, cycle, concat, intersperse, with_index, chunks, windows, chunk_by, chunk_equal, permutations, combinations. An adapter is lazy: it reads nothing until a terminal asks it for elements.
  • Terminals read the source and return a value: reduce, try_reduce, map_reduce, find, find_index, find_map, each, any_match, all_match, contains, is_empty, first, last, get, count, count_by, min, max, min_by, max_by, sum, sum_by, product, product_by, mean, mean_by, sort, sort_by, sort_with, partition, group_by, frequencies, reverse, transpose.
  • Collectors are the terminals that build a collection: to_list, to_vector, to_set and to_map. String.join joins an Iter<String> into one string.
  • Constructors make a source from a value: from, repeat, iterate. Each is infinite.

A List, Vector or Set has no map or filter of its own. To get a List back from a List, end the chain with a collector: Iter.map(xs, f) |> Iter.to_list(). A collection has a function of its own only where the result differs: String.reverse returns a String, and Iter.reverse returns a List.

Iter.count returns at once for a source that stores or can compute its count (List, Vector, Map, Set, Maybe, a bounded range whose element type can count steps) and walks any other source to its end.

Iter.loop repeats a function with no source at all.

Iter.reduce starts from its from parameter, written before the callback: Iter.reduce(xs, 0, Int.add) and Iter.reduce(xs, 0, fn sum, x -> sum + x) are the same fold, 0 for an empty xs; piped, xs |> Iter.reduce(0, Int.add). A call without it is the ordinary missing-argument error.

There is no first-element fallback, so a reduction never fails at run time for an empty source. For the least or greatest element, which an empty source does not have, use Iter.min and Iter.max: each returns a Maybe, None when the source is empty.

Iter.scan, Iter.map_reduce and Iter.try_reduce take their starting value the same way, and so does Iter.loop, which has no source: Iter.loop(0, step). Iter.scan is lazy and yields each state after the starting value, one per element; Iter.map_reduce reads the whole source and returns the final state with the outputs in order, (start, []) for an empty source.

break and continue work in every Iter callback, and each function’s doc says what they do there. In Iter.reduce, continue skips an element and break value ends the fold with value.

A named function that uses break or continue acts only on an iteration it is directly the callback of, so it is passed as the callback itself and never called: Iter.map(xs, keep), or after the starting value for a fold, Iter.reduce(xs, 0, add_until_zero). See helper functions that break or continue.

Iter.from(0), Iter.iterate(seed, step), Iter.repeat(x), Iter.cycle(xs), Range.from(n) and Range.naturals never end on their own, and say so: Iter.is_infinite is True for them. A terminal that has to reach the end (to_list, count, reduce, sum, max, sort, String.join, …) traps on such a source before it reads anything, instead of running until memory runs out:

line 3: `Iter.to_list` of an infinite iterator (`Iter.repeat`) never finishes; limit it with `Iter.take` or `Iter.take_while`

When the whole pipeline is written where the terminal is, the checker reports the same text as a compile error.

Limit an infinite source with Iter.take(n) or Iter.take_while(pred) before such a terminal, or use a terminal that stops early: Iter.find, any_match, all_match, first, get, contains, is_empty, or a reduce whose callback can break.

is_infinite is True for Iter.repeat, Iter.from, Iter.iterate (whose step cannot break), Range.from, Range.naturals, Range.step_by of an unbounded range whose step moves, and Iter.cycle of a source that is infinite or knows a non-zero count. The adapters carry it:

AdapterInfinite when
map, filter, drop, drop_while, with_index, intersperse, scan, chunk_by, chunk_equal, flat_map, flatten, Maybe.valuesthe source is, unless the callback can break
chunks(n)the source is
cyclethe source is, or knows a count above zero
concat(a, b)either is
zip(a, b)both are
take, take_whilenever

filter of an infinite source stays infinite even when nothing passes, and flat_map and flatten are infinite only through their outer source. Iter.take(n) knows its count: n over an infinite source, and the lesser of n and the source’s count when it has one.

The terminals that trap on an infinite source are to_list, to_vector, to_set, to_map, count, last, reverse, transpose, permutations, combinations, sort, sort_by, sort_with, partition, group_by, frequencies, min, max, min_by, max_by, sum, sum_by, product, product_by, mean, mean_by, count_by, String.join, Result.partition, Task.spawn_all, Supervisor.spawn_all, and reduce, each and map_reduce when their callback cannot break. The ones that may stop early do not: first, find, any_match, all_match, contains, get, is_empty, each_while, Maybe.collect, Result.collect, and a reduce, each or map_reduce whose callback can break.

A source that never ends and does not say so, such as a take_while whose predicate never fails, is not caught: a terminal that has to reach its end never returns.

A source can be run again: binding x = Iter.map(xs, f) and consuming x twice yields the same elements both times, because a source walks a value that never changes. A stream’s iterators (Reader.lines, Reader.chunks, io.lines) are the exception: they read the stream as they run, so a second run carries on where the first stopped.

Iter.to_map and String.join check their element types at compile time. A source whose element type is not a (K, V) pair or a String is a type error:

Iter.to_map([1, 2, 3]) // error: argument 1: expected Iter<(K, V)>, got List<Int>

String.join([1, 2, 3], ", ") // error: list element type mismatch: expected String, got Int

Iter.sum is bounded by where T: Add<T, T> and Summable, so an empty source sums to the type’s empty sum, and a type without the two impls is a compile error at the call: Iter.sum([True]) reports Bool does not implement Summable (required by `where T: Summable`), and the same for Add<Bool, Bool>. Iter.product is bounded the same way by where T: Multiply<T, T> and Productable. Iter.mean is bounded by where T: Averageable<R>, whose impl gives the mean’s type R: a Float for Ints and Floats, a Decimal for Decimals, a Duration for Durations.

interface Iter<T>
    fn each_while(collection: self, yield: (T) -> Bool) -> Bool
    fn known_count(_collection: self) -> Maybe<Int>
    fn is_infinite(_collection: self) -> Bool
end

What every source implements: one function, each_while, that walks the source’s own elements and hands each one to yield.

yield returns False to ask the source to stop. each_while returns True when the source ran to its end and False when the consumer stopped it early. Every function in this module is built on it, so a type that implements each_while gets all of them.

each_while reads a value that never changes, so running the same source twice yields the same elements. A stream’s iterators (Reader.lines) read the stream as they run, and do not.

List, Vector, Set, Map, String, Maybe, Bytes and ranges over Discrete values (Int, Codepoint) implement Iter. To implement it for a type of your own, walk the structure and stop as soon as yield says to:

pub struct Countdown
    from: Int
end

impl Iter for Countdown
    fn each_while(c: Countdown, yield: (Int) -> Bool) -> Bool
        if c.from <= 0 then
            True
        else
            if yield(c.from) then each_while(Countdown{from: c.from - 1}, yield) else False
        end
    end
end
fn each_while(collection: self, yield: (T) -> Bool) -> Bool

interface Iter

fn known_count(_collection: self) -> Maybe<Int>

interface Iter

Some(n) when the source can say how many elements it yields without walking them, as a List or a bounded Int range can. None when it cannot (a filtered chain, a String) or never ends (is_infinite reports that). Iter.count asks it first. Iter.take(n) knows its count when its source does or never ends.

fn is_infinite(_collection: self) -> Bool

interface Iter

True when the source never ends on its own, so a terminal that has to reach its end (Iter.to_list, Iter.count, Iter.sum, …) could never return. Such a terminal traps before it reads anything instead of running until memory runs out. False means the source may end. The sources that never end (Iter.repeat, Iter.from, Iter.iterate, Iter.cycle of a non-empty source, Range.from) return True, and so does every lazy adapter over one that cannot stop it; Iter.take and Iter.take_while can.

A type of your own returns False unless its impl writes this function.

fn loop<S>(from: S, f: (S) -> S) -> S

type function on Iter

Calls f again and again until it breaks, and returns the value it broke with. It walks no collection: use it to repeat a step until a condition holds, as a while loop does in other languages.

Each round gets the state the round before returned, and the first gets from: Iter.loop(0, fn n -> ...), or Iter.loop(0, step) with a named function. break value ends the loop with value, and a bare break ends it with the current state. continue starts the next round with the state unchanged. A loop that never breaks never ends.

A loop with no state takes the callback alone, Iter.loop(fn -> ...). It ends on a bare break and returns Unit.

The state, the break value and the result are one type, S.

first_power_over_100 = Iter.loop(1, fn n ->
    if n > 100 then
        break n
    else
        n * 2
    end
end)

assert first_power_over_100 == 128

assert Iter.loop(0, fn n ->
    if n >= 3 then
        break
    else
        n + 1
    end
end) == 3

assert Iter.loop(fn ->
    break
end) == Unit
fn reduce<T, U>(source: Iter<T>, from: U, f: (U, T) -> U) -> U

type function on Iter

Folds the elements into one value. It starts from from, calls f(acc, x) with the value so far and each element in turn, and takes what f returns as the value so far for the next element. The result is the last one, or from for an empty source.

Iter.reduce(xs, 0, fn acc, x -> acc + x) adds the elements up, and Iter.reduce(xs, 0, Int.add) is the same fold with a named function. Iter.sum, Iter.count, Iter.min and Iter.max are folds already written.

In the callback, continue skips the element and keeps the value so far, break value ends the fold with value, and a bare break ends it with the value so far.

assert Iter.reduce([1, 2, 3], 0, fn acc, x -> acc + x) == 6
assert Iter.reduce([1, 2, 3], 10, Int.add) == 16
assert Iter.reduce([], 0, fn acc, x -> acc + x) == 0
assert Iter.reduce(["a", "b"], "", fn text, s -> "${text}${s}!") == "a!b!"

until_zero = Iter.reduce([4, 5, 0, 6], 0, fn acc, x ->
    if x == 0 then
        break
    else
        acc + x
    end
end)

assert until_zero == 9
fn scan<T, U>(source: Iter<T>, from: U, f: (U, T) -> U) -> Iter<U>

type function on Iter

Lazy: runs a fold and yields each state after it. The starting value is from, as in Iter.reduce, and is not itself yielded, so there is one state per element and an empty source yields nothing.

In the callback, continue skips the element: no state is yielded and the state stays as it was. break value yields value as the last state, then stops; a bare break stops without yielding.

running = [3, 1, 4] |> Iter.scan(0, fn total, x -> total + x) |> Iter.to_list()
assert running == [3, 4, 8]

peaks = [2, 5, 3, 7] |> Iter.scan(0, fn peak, x -> Int.max(peak, x)) |> Iter.to_list()
assert peaks == [2, 5, 5, 7]
fn map_reduce<T, U, A>(source: Iter<T>, from: A, f: (A, T) -> (A, U)) -> (A, List<U>)

type function on Iter

Maps each element with a state threaded through, and returns the final state with the outputs in order. The callback takes the state and an element and returns (next_state, output), state first as in Iter.reduce; the starting state is from. An empty source returns the starting state and no outputs. It reads the whole source.

In the callback, continue skips the element: no output, and the state stays as it was. break (state, output) keeps that state and output, then stops; a bare break stops with the state and outputs so far.

(total, running) = Iter.map_reduce([1, 2, 3], 0, fn sum, x -> (sum + x, sum + x))
assert running == [1, 3, 6]
assert total == 6

lines = ["a", "abc", "ab"]

(width, rows) =
    lines
    |> Iter.reverse()
    |> Iter.map_reduce(0, fn width, line ->
        width = Int.max(width, String.length(line))
        (width, String.pad_end(line, width))
    end)

assert rows == ["ab", "abc", "a  "]
assert width == 3

none: List<String> = []
assert Iter.map_reduce(none, 0, fn n, s -> (n + 1, s)) == (0, [])
fn find<T>(source: Iter<T>, f: (T) -> Bool) -> Maybe<T>

type function on Iter

The first element for which f returns True, or None when there is none. It stops at that element, so it ends on an infinite source that holds one.

assert Iter.find([1, 2, 3, 4], fn n -> n > 2) == Some(3)
assert Iter.find([1, 2], fn n -> n > 99) == None
assert Iter.find(Iter.from(1), fn n -> n * n > 50) == Some(8)
fn find_map<T, U>(source: Iter<T>, f: (T) -> Maybe<U>) -> Maybe<U>

type function on Iter

Applies f to each element in turn and returns the first Some it gives, or None when it gives none. Stops at that element, so it ends on an infinite source that holds one. It is Iter.find for a search whose test also computes the result.

assert Iter.find_map(["x", "12", "7"], String.to_int) == Some(12)
assert Iter.find_map(["x", "y"], String.to_int) == None

first_square_over_50 =
    Iter.from(1)
    |> Iter.find_map(fn n -> if n * n > 50 then Some(n * n) else None)

assert first_square_over_50 == Some(64)
fn try_reduce<T, U, E>(source: Iter<T>, from: U, f: (U, T) -> Result<U, E>) -> Result<U, E>

type function on Iter

Folds with a step that can fail: starts from from, applies f to the state and each element in turn, and returns Ok of the final state, or the first Err the step gives. Stops at that element, so it reads no further and ends on an infinite source that fails. An empty source returns Ok(from). Use it, not Iter.reduce with ? on the accumulator, which visits every element.

fn add_digit(total: Int, text: String) -> Result<Int, String>
    case String.to_int(text)
        Some(n) -> Ok(total + n)
        None    -> Err("not a number: ${text}")
    end
end

assert Iter.try_reduce(["1", "2", "3"], 0, add_digit) == Ok(6)
assert Iter.try_reduce(["1", "x", "3", "y"], 0, add_digit) == Err("not a number: x")
assert Iter.try_reduce([], 10, add_digit) == Ok(10)

over_ten =
    Iter.from(1)
    |> Iter.try_reduce(0, fn total, n ->
        if total > 10 then Err(total) else Ok(total + n)
    end)

assert over_ten == Err(15)

guarded =
    [1, 2, 3, 4]
    |> Iter.map(fn n ->
        if n == 4 then unreachable "read past the Err" else n
    end)
    |> Iter.try_reduce(0, fn total, n -> if n == 3 then Err(total) else Ok(total + n))

assert guarded == Err(3)
fn find_index<T>(source: Iter<T>, f: (T) -> Bool) -> Maybe<NonNegativeInt>

type function on Iter

The zero-based index of the first element for which f returns True, or None when there is none. It stops at that element, so it ends on an infinite source that holds one. Iter.find returns the element itself.

assert Iter.find_index(["a", "b", "c"], &(&1 == "b")) == Some(1)
assert Iter.find_index([1, 2], &(&1 > 99)) == None
assert Iter.find_index(Iter.from(10), &(&1 % 7 == 0)) == Some(4)
fn sort_with<T>(source: Iter<T>, compare: (T, T) -> Ordering) -> List<T>

type function on Iter

The elements as a List, sorted by compare, which returns the Ordering of two elements. The sort is stable: elements that compare Equal keep their order. It reads the whole source, of any kind: a List, a range, a lazy chain.

Use it for an order the element type does not have. When the elements are Comparable, Iter.sort sorts them in their own order and Iter.sort_by by a key.

assert Iter.sort_with([3, 1, 2], Int.compare) == [1, 2, 3]
fn sort<T>(source: Iter<T>, direction: Direction = Direction.Ascending) -> List<T> where T: Comparable

type function on Iter

The elements as a List in ascending order, by the element type’s Comparable impl. .Descending (a Direction, from std::comparable) sorts from greatest to least. The sort is stable: equal elements keep their order. It reads the whole source, of any kind: a List, a range, a lazy chain.

assert Iter.sort([3, 1, 2]) == [1, 2, 3]
assert Iter.sort(["pear", "fig", "apple"]) == ["apple", "fig", "pear"]
assert Iter.sort([3, 1, 2], .Descending) == [3, 2, 1]
fn sort_by<T, K>(source: Iter<T>, direction: Direction = Direction.Ascending, key: (T) -> K) -> List<T> where K: Comparable

type function on Iter

The elements as a List, sorted by the Comparable key that key returns for each: Iter.sort_by(people, .age) is the people from youngest to oldest. .Descending sorts from the greatest key to the least. The sort is stable: elements with equal keys keep their order.

direction comes before key. A call may leave it out when key is written as a lambda, a capture or a field accessor (Iter.sort_by(xs, .k)).

assert Iter.sort_by(["bb", "a", "ccc"], &String.length(&1)) == ["a", "bb", "ccc"]
assert Iter.sort_by([{k: 2}, {k: 1}], .k) == [{k: 1}, {k: 2}]
assert Iter.sort_by(["bb", "a", "ccc"], .Descending, String.length) == ["ccc", "bb", "a"]
fn each<T>(source: Iter<T>, f: (T) -> Unit) -> Unit

type function on Iter

Calls f with each element in turn and returns Unit. Use it when the callback is run for what it does, such as printing; to build a value from the elements, use Iter.map or Iter.reduce.

In the callback, continue goes on to the next element and break stops the walk.

import std::io

printed = io.capture("", fn -> Iter.each(["pear", "fig"], io.print))
assert printed.output == "pear\nfig\n"

assert Iter.each([1, 2, 3], fn _n -> Unit) == Unit
fn any_match<T>(source: Iter<T>, f: (T) -> Bool) -> Bool

type function on Iter

Whether f returns True for at least one element. It stops at the first one that matches. An empty source has none, so the result is False.

assert Iter.any_match([1, 2, 3], fn n -> n > 2)
refute Iter.any_match([1, 2], fn n -> n > 99)
refute Iter.any_match([], fn n -> n > 0)
fn contains<T>(source: Iter<T>, x: T) -> Bool where T: Equatable

type function on Iter

Whether an element is == to x. It checks each element in turn and stops at the first match, so it ends on an infinite source that holds x. It works on any source, a lazy chain included; a collection’s own contains (the Contains interface, which in uses) may be faster.

assert Iter.contains([1, 2, 3], 2)
refute Iter.contains(Iter.map([1, 2], &(&1 * 10)), 2)
assert Iter.contains(Iter.from(0), 1_000)
fn all_match<T>(source: Iter<T>, f: (T) -> Bool) -> Bool

type function on Iter

Whether f returns True for every element. It stops at the first one that does not match. An empty source has none that fail, so the result is True.

assert Iter.all_match([2, 4, 6], fn n -> n > 0)
refute Iter.all_match([2, -4, 6], fn n -> n > 0)
assert Iter.all_match([], fn n -> n > 0)
fn is_empty<T>(source: Iter<T>) -> Bool

type function on Iter

Whether the source yields no element. It reads at most one, so it works on an infinite source.

assert Iter.is_empty([])
refute Iter.is_empty([1])
fn first<T>(source: Iter<T>) -> Maybe<T>

type function on Iter

The first element, or None when the source is empty. It reads at most one element, so it works on an infinite source.

assert Iter.first([1, 2, 3]) == Some(1)
assert Iter.first([]) == None
fn last<T>(source: Iter<T>) -> Maybe<T>

type function on Iter

The last element, or None when the source is empty. It reads the whole source, so it traps on an infinite one.

assert Iter.last([1, 2, 3]) == Some(3)
assert Iter.last([]) == None
fn get<T>(source: Iter<T>, index: Int) -> Maybe<T>

type function on Iter

The element at index, counting from 0, or None when the source has none there: index is negative, or the source is too short. It walks the source from its start and stops at index, so a far index takes that many steps, and it works on an infinite source. A Vector reads any index in one step with Vector.get.

assert Iter.get([10, 20, 30], 0) == Some(10)
assert Iter.get([10, 20, 30], 1) == Some(20)
assert Iter.get([10, 20, 30], 9) == None
assert Iter.get([10, 20, 30], -1) == None
assert Iter.get("héllo", 1) == Some("é")
fn partition<T>(source: Iter<T>, f: (T) -> Bool) -> (List<T>, List<T>)

type function on Iter

Splits the elements into two Lists: those for which f returns True, then the rest. Each keeps the source’s order. It reads the whole source.

assert Iter.partition([1, 2, 3, 4], &(&1 > 2)) == ([3, 4], [1, 2])
fn group_by<T, K>(source: Iter<T>, key_fn: (T) -> K) -> Map<K, NonEmptyList<T>>

type function on Iter

Groups the elements by the key key_fn returns for each, as a Map from each key to its elements. The keys are in the order each first appears, and each group keeps the source’s order. A group is a NonEmptyList, since a key is in the map only for an element that produced it. It reads the whole source.

groups = Iter.group_by([1, 2, 3, 4], fn n -> n % 2)
assert groups == {1 => [1, 3], 0 => [2, 4]}
assert groups |> Map.get(1) |> Maybe.map(NonEmptyList.first) == Some(1)

by_length = Iter.group_by(["fig", "pear", "plum"], String.length)
assert by_length == {3 => ["fig"], 4 => ["pear", "plum"]}
fn frequencies<T>(source: Iter<T>) -> Map<T, Int>

type function on Iter

Counts how often each element occurs, as a Map from each distinct element to its count. The keys are in the order each first appears. Iter.group_by keeps the elements themselves instead of their count. It reads the whole source.

assert Iter.frequencies(["a", "b", "a"]) == {"a" => 2, "b" => 1}
assert Iter.frequencies("banana") |> Map.keys() == ["b", "a", "n"]
assert Iter.frequencies([3, 1, 3, 3]) |> Map.get(3) == Some(3)

empty: List<Int> = []
assert Iter.frequencies(empty) |> Map.size() == 0
fn to_list<T>(source: Iter<T>) -> List<T>

type function on Iter

The elements of source as a List, in order. It is the step that ends a chain of lazy adapters and runs it. A List is returned as it is.

An infinite source (Iter.is_infinite) traps before anything is read from it, since the List could never be finished.

assert [1, 2, 3] |> Iter.map(fn n -> n * 2) |> Iter.to_list() == [2, 4, 6]
assert Iter.to_list(1..=3) == [1, 2, 3]
assert Iter.to_list("hey") == ["h", "e", "y"]
assert Iter.from(0) |> Iter.take(3) |> Iter.to_list() == [0, 1, 2]
fn to_vector<T>(source: Iter<T>) -> Vector<T>

type function on Iter

The elements of source as a Vector, in order. The vector is built in one pass, with no List in between, and a source that knows its count (a List, Set or Map) sizes it once. A Vector is returned as it is.

assert Iter.to_vector([1, 2, 3]) == [1, 2, 3]
assert 1..=3 |> Iter.to_vector() == [1, 2, 3]

tens =
    [1, 2, 3, 4]
    |> Iter.filter(fn x -> x % 2 == 0)
    |> Iter.map(&(&1 * 10))
    |> Iter.to_vector()

assert tens == [20, 40]

empty: List<Int> = []
assert Iter.to_vector(empty) == []
fn to_set<T>(source: Iter<T>) -> Set<T>

type function on Iter

The elements of source as a Set, which keeps one of each.

assert Iter.to_set([1, 2, 2, 3]) == [1, 2, 3]
assert 1..=3 |> Iter.to_set() == [1, 2, 3]
fn with_index<T>(source: Iter<T>) -> Iter<(NonNegativeInt, T)>

type function on Iter

Lazy: pairs each element of source with a zero-based index.

assert ["a", "b", "c"] |> Iter.with_index() |> Iter.to_list() == [(0, "a"), (1, "b"), (2, "c")]
fn take<T>(source: Iter<T>, n: Int) -> Iter<T>

type function on Iter

Lazy: yields the first n elements of source, or all of them when it has fewer. An n of 0 or less yields nothing.

It is how an infinite source is limited: the result is never infinite, and its known_count is n when source never ends, or the lesser of n and the source’s own count when it has one.

assert Iter.from(0) |> Iter.take(3) |> Iter.to_list() == [0, 1, 2]
refute Iter.repeat("x") |> Iter.take(3) |> Iter.is_infinite()
assert Iter.repeat("x") |> Iter.take(3) |> Iter.known_count() == Some(3)
assert [1, 2] |> Iter.take(5) |> Iter.known_count() == Some(2)
fn cycle<T>(source: Iter<T>) -> Iter<T>

type function on Iter

Lazy: yields the elements of source over and over. An empty source yields nothing. It is is_infinite when source is, or when source knows its count and it is not zero; a source that may be empty (a filtered one) leaves it unknown.

assert [1, 2, 3]
|> Iter.cycle()
|> Iter.take(7)
|> Iter.to_list() == [1, 2, 3, 1, 2, 3, 1]

assert [1, 2] |> Iter.cycle() |> Iter.is_infinite()
refute [] |> Iter.cycle() |> Iter.is_infinite()
assert [1, 2] |> Iter.filter(&(&1 > 5)) |> Iter.cycle() |> Iter.to_list() == []
fn concat<T>(a: Iter<T>, b: Iter<T>) -> Iter<T>

type function on Iter

Lazy: yields all elements of a, then all of b. Infinite when either is.

assert Iter.concat([1, 2], [3, 4]) |> Iter.to_list() == [1, 2, 3, 4]
assert Iter.concat([1, 2], Iter.from(3)) |> Iter.is_infinite()
fn intersperse<T>(source: Iter<T>, separator: T) -> Iter<T>

type function on Iter

Lazy: yields the elements of source with separator between each two neighbors, so n elements become 2n - 1, and none stay none. Infinite when source is.

assert ["a", "b", "c"] |> Iter.intersperse(",") |> Iter.to_list() == ["a", ",", "b", ",", "c"]
assert [1] |> Iter.intersperse(0) |> Iter.to_list() == [1]
assert Iter.from(1) |> Iter.intersperse(0) |> Iter.take(4) |> Iter.to_list() == [1, 0, 2, 0]

verses = [["one", "two"], ["three"]]
lines = verses |> Iter.intersperse([""]) |> Iter.flatten() |> Iter.to_list()
assert lines == ["one", "two", "", "three"]
fn zip<T, U>(a: Iter<T>, b: Iter<U>) -> Iter<(T, U)>

type function on Iter

Lazy: pairs the elements of two sources, the first of each, then the second of each, and so on. It stops when either runs out, so it is infinite only when both are.

assert Iter.zip([1, 2, 3], ["a", "b"]) |> Iter.to_list() == [(1, "a"), (2, "b")]
assert Iter.zip(["a", "b"], Iter.from(0)) |> Iter.to_list() == [("a", 0), ("b", 1)]
assert Iter.zip(Iter.repeat("a"), Iter.from(0)) |> Iter.is_infinite()
fn take_while<T>(source: Iter<T>, pred: (T) -> Bool) -> Iter<T>

type function on Iter

Lazy: yields the elements of source up to the first for which pred returns False, and stops there.

In the callback, break True yields the current element and then stops, break False or a bare break stops without it, and continue skips it and goes on.

assert Iter.from(1)
|> Iter.take_while(&(&1 < 4))
|> Iter.to_list() == [1, 2, 3]

refute Iter.from(1) |> Iter.take_while(&(&1 < 4)) |> Iter.is_infinite()
fn map<T, U>(source: Iter<T>, f: (T) -> U) -> Iter<U>

type function on Iter

Lazy: yields f(x) for each element x of source, in order. The result is an Iter, and f runs only as something reads it: end the chain with Iter.to_list() for a List, or with another terminal such as Iter.sum.

In the callback, continue skips the element, break value yields value and then stops, and a bare break stops. The result is infinite when source is, unless the callback can break.

assert [1, 2, 3] |> Iter.map(fn n -> n * 10) |> Iter.to_list() == [10, 20, 30]
assert ["a", "bb"] |> Iter.map(String.length) |> Iter.to_list() == [1, 2]
assert 1..=3 |> Iter.map(fn n -> n * n) |> Iter.sum() == 14
fn filter<T>(source: Iter<T>, pred: (T) -> Bool) -> Iter<T>

type function on Iter

Lazy: yields the elements for which pred returns True, in order, and drops the rest. Iter.reject keeps the others. End the chain with Iter.to_list() for a List.

In the callback, continue drops the element, break True keeps it and then stops, and break False or a bare break drops it and stops.

The filter of an infinite source is infinite even if nothing passes: collecting it never finishes either way. A predicate that can break may end it, so that filter is not known to be infinite.

assert [1, 2, 3, 4] |> Iter.filter(fn n -> n > 2) |> Iter.to_list() == [3, 4]
assert ["fig", "", "pear"] |> Iter.filter(fn s -> s != "") |> Iter.to_list() == ["fig", "pear"]
assert 1..=10 |> Iter.filter(fn n -> n % 2 == 0) |> Iter.count() == 5
assert Iter.from(0) |> Iter.filter(fn n -> n % 2 == 0) |> Iter.is_infinite()
fn reject<T>(source: Iter<T>, pred: (T) -> Bool) -> Iter<T>

type function on Iter

Lazy: drops the elements where pred returns true and keeps the rest, the opposite of Iter.filter.

The reject of an infinite source is infinite even if nothing is kept.

assert [1, 2, 3, 4] |> Iter.reject(&(&1 > 2)) |> Iter.to_list() == [1, 2]
assert Iter.from(0) |> Iter.reject(&(&1 % 2 == 0)) |> Iter.is_infinite()
fn drop<T>(source: Iter<T>, n: Int) -> Iter<T>

type function on Iter

Lazy: skips the first n elements of source and yields the rest. An n of 0 or less skips nothing.

assert [1, 2, 3, 4] |> Iter.drop(2) |> Iter.to_list() == [3, 4]
fn drop_while<T>(source: Iter<T>, pred: (T) -> Bool) -> Iter<T>

type function on Iter

Lazy: skips elements while pred returns True, then yields the first for which it does not and every element after it.

assert [1, 2, 3, 1] |> Iter.drop_while(&(&1 < 3)) |> Iter.to_list() == [3, 1]
fn flat_map<T, U>(source: Iter<T>, f: (T) -> Iter<U>) -> Iter<U>

type function on Iter

Lazy: calls f with each element of source and yields every element of what it returns, in order: a map whose results are joined into one sequence. An f that returns a Maybe keeps the Some values and drops the Nones.

assert [1, 2, 3] |> Iter.flat_map(fn x -> [x, x * 10]) |> Iter.to_list() == [1, 10, 2, 20, 3, 30]

words = ["a b", "c"] |> Iter.flat_map(fn s -> String.split(s, " ")) |> Iter.to_list()
assert words == ["a", "b", "c"]

assert ["1", "x", "3"] |> Iter.flat_map(String.to_int) |> Iter.to_list() == [1, 3]
fn chunks<T>(source: Iter<T>, size: PositiveInt) -> Iter<NonEmptyList<T>>

type function on Iter

Lazy: yields adjacent chunks of size elements as NonEmptyLists. The final chunk may be shorter. The size is a PositiveInt.

assert [1, 2, 3, 4, 5] |> Iter.chunks(2) |> Iter.to_list() == [[1, 2], [3, 4], [5]]
assert [1, 2, 3] |> Iter.chunks(2) |> Iter.map(&NonEmptyList.last(&1)) |> Iter.to_list() == [2, 3]
fn windows<T>(source: Iter<T>, size: PositiveInt) -> Iter<NonEmptyList<T>>

type function on Iter

Lazy: yields every run of size neighboring elements as a NonEmptyList, one starting at each element, so the runs overlap: [1, 2, 3, 4] with size 2 gives [1, 2], [2, 3] and [3, 4]. The size is a PositiveInt. A source with fewer than size elements yields none, and it is infinite when source is.

assert [1, 2, 3, 4] |> Iter.windows(2) |> Iter.to_list() == [[1, 2], [2, 3], [3, 4]]
assert [1, 2] |> Iter.windows(3) |> Iter.to_list() == []

rises =
    [3, 5, 4, 8]
    |> Iter.windows(2)
    |> Iter.count_by(fn w -> w == Iter.sort(w))

assert rises == 2
assert Iter.from(1) |> Iter.windows(3) |> Iter.first() == Some([1, 2, 3])
fn chunk_by<T, K>(source: Iter<T>, key_fn: (T) -> K) -> Iter<NonEmptyList<T>> where K: Equatable

type function on Iter

Lazy: yields adjacent runs whose elements produce equal keys, each a NonEmptyList. Unlike group_by, this never reorders or merges non-adjacent elements. To group runs of equal elements themselves, use Iter.chunk_equal.

assert [1, 2, 4, 5, 3] |> Iter.chunk_by(&(&1 % 2)) |> Iter.to_list() == [[1], [2, 4], [5, 3]]

assert ["ant", "ape", "bee", "bat", "cat"]
    |> Iter.chunk_by(&String.contains(&1, "a"))
    |> Iter.to_list()
    |> List.equal([["ant", "ape"], ["bee"], ["bat", "cat"]])
fn chunk_equal<T>(source: Iter<T>) -> Iter<NonEmptyList<T>> where T: Equatable

type function on Iter

Lazy: yields each run of equal neighboring elements as a NonEmptyList, so Iter.chunk_equal(xs) is Iter.chunk_by(xs, fn x -> x). Equal elements that are not neighbors land in separate runs; for one group per value, use Iter.group_by or Iter.frequencies. A run is never empty, and an empty source yields none. It is infinite when source is.

assert [1, 1, 2, 2, 1] |> Iter.chunk_equal() |> Iter.to_list() == [[1, 1], [2, 2], [1]]
assert "aaabcc" |> Iter.chunk_equal() |> Iter.map(Iter.count) |> Iter.to_list() == [3, 1, 2]
assert Iter.from(0) |> Iter.chunk_equal() |> Iter.first() == Some([0])
fn permutations<T>(items: Iter<T>) -> Iter<List<T>>

type function on Iter

Lazy: every ordering of the elements of items, each as a List, in lexicographic order of the positions the elements come from, so a sorted source gives its orderings sorted. Elements are told apart by position, not by value: [1, 1] gives [1, 1] twice. n elements give n! orderings, and none give one, the empty list. items is read at once and must end; each ordering is built only when the walk reaches it.

assert [1, 2, 3] |> Iter.permutations() |> Iter.to_list() == [
    [1, 2, 3],
    [1, 3, 2],
    [2, 1, 3],
    [2, 3, 1],
    [3, 1, 2],
    [3, 2, 1],
]

assert 1..=10 |> Iter.permutations() |> Iter.get(1) == Some([1, 2, 3, 4, 5, 6, 7, 8, 10, 9])
assert Iter.permutations(["a"]) |> Iter.count() == 1
fn combinations<T>(items: Iter<T>, k: Int) -> Iter<List<T>>

type function on Iter

Lazy: every choice of k elements of items, each as a List that keeps the order of the source, in lexicographic order of the positions the elements come from. Elements are told apart by position, not by value. n elements give n choose k lists; a k of 0 gives one, the empty list, and a k below 0 or above n gives none. items is read at once and must end; each choice is built only when the walk reaches it.

assert ["a", "b", "c", "d"] |> Iter.combinations(2) |> Iter.to_list() == [
    ["a", "b"],
    ["a", "c"],
    ["a", "d"],
    ["b", "c"],
    ["b", "d"],
    ["c", "d"],
]

assert 1..=10 |> Iter.combinations(5) |> Iter.count() == 252
assert [1, 2] |> Iter.combinations(3) |> Iter.to_list() == []
fn from(start: Int) -> Iter<Int>

type function on Iter

An infinite source that counts up from start: start, start + 1, start + 2, and so on. Limit it with Iter.take or Iter.take_while before collecting it.

assert Iter.from(10) |> Iter.take(3) |> Iter.to_list() == [10, 11, 12]
assert Iter.is_infinite(Iter.from(10))
fn repeat<T>(x: T) -> Iter<T>

type function on Iter

An infinite source that yields x over and over.

assert Iter.repeat("ha") |> Iter.take(3) |> Iter.to_list() == ["ha", "ha", "ha"]
assert Iter.repeat("ha") |> Iter.map(&String.length(&1)) |> Iter.is_infinite()
fn iterate<T>(seed: T, step: (T) -> T) -> Iter<T>

type function on Iter

An infinite source that starts at seed and applies step to get each next element: seed, step(seed), step(step(seed)), and so on.

In the step callback:

  • A plain result v yields the current state and moves on to v.
  • break v yields v as the last element, then stops.
  • A bare break stops without yielding.
  • continue is a compile error: the step’s result is the next state, so there is nothing to continue to. Skip states after the step instead, with Iter.iterate(...) |> Iter.filter(...).

It is is_infinite unless the step can break, which may end it.

assert Iter.iterate(1, &(&1 * 2))
|> Iter.take(4)
|> Iter.to_list() == [1, 2, 4, 8]

assert Iter.is_infinite(Iter.iterate(1, &(&1 * 2)))

assert Iter.iterate(0, fn n ->
    if n > 5 then
        break n
    else
        n + 1
    end
end)
    |> Iter.to_list()
    |> List.equal([0, 1, 2, 3, 4, 5, 6])
fn to_map<K, V>(source: Iter<(K, V)>) -> Map<K, V>

type function on Iter

The (key, value) pairs of source as a Map. A later pair with a key already seen replaces the earlier value.

assert Iter.to_map([("a", 1), ("b", 2)]) == {"a" => 1, "b" => 2}
fn flatten<T>(source: Iter<Iter<T>>) -> Iter<T>

type function on Iter

Lazy: yields the elements of each inner source in turn, in order: a List of Lists becomes one sequence of their elements. It reads each inner source only as it reaches it, so it works on an endless outer source.

assert Iter.flatten([[1, 2], [3], [4, 5]]) |> Iter.to_list() == [1, 2, 3, 4, 5]
assert Iter.repeat([1, 2]) |> Iter.flatten() |> Iter.take(3) |> Iter.to_list() == [1, 2, 1]
fn transpose<T>(rows: Iter<Iter<T>>) -> List<List<T>>

type function on Iter

The columns of rows, as a List of Lists: column i holds the ith element of each row long enough to have one, in row order. A ragged row adds nothing past its end, so no element is invented and none is dropped. It reads the whole source, since the first column needs every row.

assert Iter.transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]
assert Iter.transpose([[1, 2, 3], [4], [5, 6]]) == [[1, 4, 5], [2, 6], [3]]
assert Iter.transpose(Vector[Vector[1, 2], Vector[3, 4]]) == [[1, 3], [2, 4]]
assert Iter.transpose(["ab", "cd"]) == [["a", "c"], ["b", "d"]]
assert Iter.transpose([[1], []]) == [[1]]
fn reverse<T>(source: Iter<T>) -> List<T>

type function on Iter

The elements of source as a List, last first. It reads the whole source. String.reverse reverses a String into a String.

assert Iter.reverse([1, 2, 3]) == [3, 2, 1]
fn count<T>(source: Iter<T>) -> NonNegativeInt

type function on Iter

The number of elements in source. A source that stores its size (a List, Vector, Map, Set, Maybe, or a bounded range whose element type can count steps) answers at once, through known_count. Any other source, such as a String or a filtered chain, is walked to its end and counted.

It traps on an infinite source; limit one with Iter.take first. Iter.known_count returns the count only when it is known without a walk, and None otherwise.

assert Iter.count([10, 20, 30]) == 3
assert Iter.count([]) == 0
assert Iter.count("héllo") == 5
assert 1..=10 |> Iter.filter(fn n -> n % 3 == 0) |> Iter.count() == 3
assert Iter.from(0) |> Iter.take(5) |> Iter.count() == 5
fn count_by<T>(source: Iter<T>, pred: (T) -> Bool) -> NonNegativeInt

type function on Iter

The number of elements for which pred returns True: Iter.count_by(xs, pred) is Iter.filter(xs, pred) |> Iter.count(). It calls pred once per element, reads the whole source and traps on an infinite one.

assert Iter.count_by([1, 2, 3, 4, 5], &(&1 > 2)) == 3
assert Iter.count_by("banana", &(&1 == "a")) == 3
assert Iter.count_by([True, False, True], fn yes -> yes) == 2
none: List<Int> = []
assert Iter.count_by(none, &(&1 > 0)) == 0
fn min<T>(source: Iter<T>) -> Maybe<T> where T: Comparable

type function on Iter

The least element, or None for an empty source. Of equal least elements, the first wins. It reads the whole source.

assert Iter.min([3, 1, 2]) == Some(1)
assert Iter.min(["pear", "fig", "plum"]) == Some("fig")
assert Iter.min([]) == None
fn max<T>(source: Iter<T>) -> Maybe<T> where T: Comparable

type function on Iter

The greatest element, or None for an empty source. Of equal greatest elements, the first wins. It reads the whole source.

assert Iter.max([3, 1, 2]) == Some(3)
assert Iter.max(["pear", "fig", "plum"]) == Some("plum")
assert Iter.max([]) == None
fn min_by<T, K>(source: Iter<T>, key: (T) -> K) -> Maybe<T> where K: Comparable

type function on Iter

The element whose key is least, or None for an empty source. Of elements with equal least keys, the first wins. It calls key once per element.

assert Iter.min_by(["pear", "fig", "plum"], &String.length(&1)) == Some("fig")
assert Iter.min_by([(1, "a"), (0, "b"), (0, "c")], fn (n, _) -> n) == Some((0, "b"))
fn max_by<T, K>(source: Iter<T>, key: (T) -> K) -> Maybe<T> where K: Comparable

type function on Iter

The element whose key is greatest, or None for an empty source. Of elements with equal greatest keys, the first wins. It calls key once per element.

assert Iter.max_by(["pear", "fig", "plum"], &String.length(&1)) == Some("pear")
assert Iter.max_by([(1, "a"), (0, "b"), (1, "c")], fn (n, _) -> n) == Some((1, "a"))
fn sum<T>(source: Iter<T>) -> T where T: Add<T, T> and Summable

type function on Iter

The elements added up with +, left to right. An empty source sums to the type’s empty sum, T.empty_sum(): 0 for Int, 0.0 for Float, "" for String, [] for List.

Iter.sum(xs) is exactly Iter.reduce(xs, T.empty_sum(), fn total, x -> total + x), so it rounds Floats as that fold does; Decimals add exactly. Summing Maps follows Map’s +: a later map wins on a shared key. It reads the whole source, so it traps on an infinite one.

assert Iter.sum([1, 2, 3]) == 6
assert Iter.sum(1..=4) == 10
assert Iter.sum([19.99d, 5.01d]) == 25.00d
assert Iter.sum([0.5, 0.25]) == 0.75
assert Iter.sum(["a", "b", "c"]) == "abc"
assert Iter.sum([[1], [2, 3]]) == [1, 2, 3]
none: List<Int> = []
assert Iter.sum(none) == 0
fn sum_by<T, N>(source: Iter<T>, key: (T) -> N) -> N where N: Add<N, N> and Summable

type function on Iter

The sum of key of each element, added with +, left to right: Iter.sum_by(orders, .total) is the sum of the orders’ totals. An empty source sums to N.empty_sum().

Iter.sum_by(xs, key) is exactly Iter.map(xs, key) |> Iter.sum(). It reads the whole source, so it traps on an infinite one.

orders = [{id: 1, total: 5}, {id: 2, total: 7}]
assert Iter.sum_by(orders, .total) == 12
assert Iter.sum_by(["ab", "c"], String.length) == 3
assert Iter.sum_by([1.5, 2.5], &(&1 * 2.0)) == 8.0
none: List<Int> = []
assert Iter.sum_by(none, &(&1 * 2)) == 0
fn mean<T, R>(source: Iter<T>) -> Maybe<R> where T: Averageable<R>

type function on Iter

The arithmetic mean of the elements, or None for an empty source. The element type’s Averageable impl decides the result type and the rounding: Ints give a Float rounded once from the exact sum, Floats are summed with compensation, Decimals divide their exact sum with Decimal’s /, and Durations give the nearest nanosecond. A subtype is averaged as its base, so the mean of NonNegativeInt lengths is a Float. It reads the source once, so it works on a lazy source or a stream’s; it traps on an infinite one.

assert Iter.mean([1, 2, 3, 4]) == Some(2.5)
assert Iter.mean([1, 2, 4]) == Some(2.3333333333333335)
assert Iter.mean([0.5, 1.0]) == Some(0.75)
assert Iter.mean([1.0e100, 1.0, -1.0e100]) == Some(0.3333333333333333)
assert Iter.mean([1.50d, 2.25d]) == Some(1.875d)
assert Iter.mean(1..=10) == Some(5.5)
none: List<Int> = []
assert Iter.mean(none) == None
fn mean_by<T, N, R>(source: Iter<T>, key: (T) -> N) -> Maybe<R> where N: Averageable<R>

type function on Iter

The arithmetic mean of key of each element, or None for an empty source: Iter.mean_by(orders, .total) is the orders’ mean total. Iter.mean_by(xs, key) is exactly Iter.map(xs, key) |> Iter.mean(), and rounds as Iter.mean does. Calls key once per element.

orders = [{id: 1, total: 5}, {id: 2, total: 8}]
assert Iter.mean_by(orders, .total) == Some(6.5)
assert Iter.mean_by(["ab", "c"], String.length) == Some(1.5)
assert Iter.mean_by([1.5d, 2.5d], &(&1 * 2d)) == Some(4d)
none: List<String> = []
assert Iter.mean_by(none, String.length) == None
fn product<T>(source: Iter<T>) -> T where T: Multiply<T, T> and Productable

type function on Iter

The elements multiplied with *, left to right. An empty source’s product is the type’s empty product, T.empty_product(): 1 for Int, 1.0 for Float, 1d for Decimal.

Iter.product(xs) is exactly Iter.reduce(xs, T.empty_product(), fn product, x -> product * x), so it rounds Floats as that fold does. It does not stop at a zero. It reads the whole source, so it traps on an infinite one.

assert Iter.product([2, 3, 4]) == 24
assert Iter.product([0.5, 4.0]) == 2.0
assert Iter.product([1.5d, 2d]) == 3.0d
assert Iter.product(1..=5) == 120
none: List<Int> = []
assert Iter.product(none) == 1
fn product_by<T, N>(source: Iter<T>, key: (T) -> N) -> N where N: Multiply<N, N> and Productable

type function on Iter

The product of key of each element, multiplied with *, left to right. An empty source’s product is N.empty_product().

Iter.product_by(xs, key) is exactly Iter.map(xs, key) |> Iter.product(). It reads the whole source, so it traps on an infinite one.

sides = [{w: 2, h: 3}, {w: 4, h: 1}]
assert Iter.product_by(sides, .w) == 8
assert Iter.product_by(1..=3, &(&1 + 1)) == 24
none: List<Int> = []
assert Iter.product_by(none, &(&1 * 2)) == 1