lists - list manipulation
Enable with use lists;; every function is called as lists.NAME(...). Each function returns a new list and never mutates the input; commit the result with an assignment:
use io;
use lists;
def xs as list of int init [3, 1, 4, 1, 5];
$xs = lists.push($xs, 9); # append item
$xs = $xs[..len($xs) - 1]; # drop last
$xs = lists.sort($xs); # sort ascending
io.printf("first=%d last=%d\n", lists.first($xs), lists.last($xs));To build a list element by element, use the $xs[] = item; append sugar (see user-guide/types-and-values.md). It means $xs = lists.push($xs, item); but mutates the binding in place (amortized O(N) for N appends), whereas lists.push copies the whole list each pass - O(N^2) in a loop. Use lists.push when you want a fresh list and keep the original.
Functions
| Call | Returns | Notes |
|---|---|---|
lists.push(xs, item) | list | New list with item appended. In a build-a-list loop prefer the $xs[] sugar (O(N) vs this call's O(N^2)). A result over 16777216 elements (1048576 on jennifer-tiny) is an error of kind "limit". |
lists.first(xs) | element kind | Element at index 0. Empty input errors. |
lists.last(xs) | element kind | Element at the last index. Empty input errors. |
lists.reverse(xs) | list | New list, elements in reverse order. |
lists.sort(xs) | list | New list sorted ascending. See "Sort" below. |
lists.contains(xs, item) | bool | True iff item appears in xs under structural equality. |
lists.indexOf(xs, item) | int | Index of the first element equal to item (same structural equality as contains); -1 if absent. |
lists.mismatch(a, b) / lists.mismatch(a, b, from) | int | First index at or after from (default 0) where a and b differ - elements not ==, or only one list has an element there; -1 if they agree to the end. from must be in [0, max(len(a), len(b))]. |
lists.concat(a, b) | list | a's elements followed by b's. A result over 16777216 elements (1048576 on jennifer-tiny) is an error of kind "limit". |
lists.replicate(xs, n) | list | n copies of xs concatenated, as strings.replicate does for strings: lists.replicate([false], $n) is a filled list, lists.replicate([1, 0], 2) is [1, 0, 1, 0]. Elements are deep copies (lists.replicate([[0, 0]], 3) is three independent rows). A negative n errors; a result over 16777216 elements (1048576 on jennifer-tiny) is an error of kind "limit", raised before anything is built. |
lists.shuffle(xs) | list | New list, elements in uniformly random order. See "Shuffle" below. |
lists.range(start, end, step) | list of int | Walks by step while staying strictly before end. See "Range". |
lists.map(xs, fn) | list | New list of fn(x) for each x. See "Higher-order functions". |
lists.filter(xs, fn) | list | The elements where fn(x) returns true. |
lists.reduce(xs, fn, init) | element kind | Fold left: acc = fn(acc, x), starting from init. |
lists.find(xs, fn) | element kind | The first x where fn(x) is true; errors (catchable) if none. |
lists.any(xs, fn) | bool | True if fn(x) is true for any element (short-circuits). |
lists.all(xs, fn) | bool | True if fn(x) is true for every element (true for empty). |
lists.sortBy(xs, keyFn) | list | New list sorted ascending by the key keyFn(x) returns. |
lists.sortWith(xs, cmp) | list | New list sorted stably by the comparator cmp(a, b) (an int: negative puts a first). |
Higher-order functions
map / filter / reduce / find / any / all / sortBy / sortWith each take a func value (see the language guide) and call it once per element (sortWith once per comparison). A bare function name in expression position is the function value, so pass a function by name:
use lists;
func dbl(n as int) { return $n * 2; }
func isEven(n as int) { return $n % 2 == 0; }
def xs as list of int init [1, 2, 3, 4, 5];
lists.map($xs, dbl); # [2, 4, 6, 8, 10]
lists.filter($xs, isEven); # [2, 4]
lists.reduce($xs, add, 0); # sum, with func add(a as int, b as int) {...}
lists.any($xs, isEven); # true
lists.all($xs, isEven); # falsemapreturns a generic list - its element type is whatever the callback returns, checked against the declared type at the binding site, sodef names as list of string init lists.map($people, nameOf);type-checks only when every result is a string.filter/find/any/all: the callback must return abool, else a positioned error.finderrors (catchably) when nothing matches- guard with
lists.anyfirst, or wrap it intry/catch.
- guard with
sortBytakes a key extractorkeyFn(x) -> K(a comparable scalar:int/float/string/bool) and sorts ascending by that key, stably. The key is extracted once per element, sokeyFnruns O(n) times, not O(n log n). Sort descending by negating a numeric key (func neg(n as int) { return 0 - $n; }) or reversing the result. Sort structs by a field with a one-line accessor (func ageOf(p as Person) { return $p.age; }).sortWithtakes a comparatorcmp(a, b) -> int: negative whenagoes first, positive whenbdoes,0when they are equal. The sort is stable, so equal elements keep their input order. A result that is not anintis a positioned runtime error naminglists.sortWith; an error the comparator throws propagates unchanged. Use it for an ordersortBycannot express with one key: several keys, or one descending and the next ascending.cmpruns O(n log n) times (never for an empty or one-element list), sosortBystays the faster choice for a single key. A comparator that is not a consistent order (cmp(a, b)andcmp(b, a)both negative) gives some permutation of the input - never an error or a lost element.jennifer# Descending length, then ascending. func longerFirst(a as string, b as string) { if (len($a) != len($b)) { return len($b) - len($a); } if ($a < $b) { return -1; } if ($a > $b) { return 1; } return 0; } lists.sortWith(["of", "set", "a", "is"], longerFirst); # ["set", "is", "of", "a"]
Sort
lists.sort works on lists whose elements share a comparable kind:
- All elements
intorfloat(mixed allowed; int / float pairs compare exactly, no float rounding). - All elements
string- lexicographic order on the underlying rune sequence. - All elements
bool-false < true.
A list mixing strings with numbers, or containing null, list, or map elements, is a runtime error. For a custom order, lists.sortBy(xs, keyFn) sorts by the key a func value extracts, and lists.sortWith(xs, cmp) by a comparator func (see "Higher-order functions" above).
first/last versus slices
first and last return elements (the value at index 0 or len-1). A slice returns a sublist:
def xs as list of int init [10, 20, 30, 40, 50];
lists.first($xs); # 10 (an int)
lists.last($xs); # 50 (an int)
$xs[..2]; # [10, 20] (the first two)
$xs[len($xs) - 2..]; # [40, 50] (the last two)
$xs[1..]; # [20, 30, 40, 50] (all but the first)
$xs[..len($xs) - 1]; # [10, 20, 30, 40] (all but the last)lists.head, tail, pop and slice were removed in 0.28.0; use slices.
Argument order
lists.contains puts the haystack first and the needle second (lists.contains($xs, item)), mirroring strings.contains($s, $sub) (not PHP's in_array($needle, $haystack) order).
Shuffle
lists.shuffle(xs) returns a uniformly random permutation of xs (Durstenfeld's Fisher-Yates, O(n)). It shares the random source of math.rand / math.randInt / math.randSeed, so math.randSeed(N) before a shuffle makes the result deterministic across runs:
use lists;
use math;
math.randSeed(1);
def a as list of int init lists.shuffle([1, 2, 3, 4, 5]);
math.randSeed(1);
def b as list of int init lists.shuffle([1, 2, 3, 4, 5]);
# $a and $b are byte-identical permutations.Empty and single-element inputs are returned as copies. lists.shuffle does not need use math;.
Range
A run of consecutive integers is the language's start..end: lazy in a for, a list where one is declared. lists.range is for the sequences .. has no form for, those with a step, counting down included. The two-bound lists.range(start, end) was removed in 0.28.0: write start..end, and lists.range(start, end, -1) where it counted down.
Both are half-open: end is exclusive, as in slices, Python range, Go slicing and Rust ... Rationale (including why this departs from Jennifer's English-reading default): design-decisions.md > Half-open ranges.
- Index alignment.
0..len($xs)gives exactly the valid indices for a list oflen($xs)elements, matching how$xs[i]indexing works. - Composability.
lists.concat(a..b, b..c)is exactlya..c. Partitioning a range never duplicates or skips the boundary.
For the "count from 1 to N inclusive" idiom, write 1..N + 1.
lists.range(start, end, step) walks by step, always stopping strictly before end. A positive step requires start <= end, a negative step start > end; the step must be non-zero (positional error).
lists.range materialises its whole list, so the element count is capped (the same cap as the .. operator); a span over it is a catchable error. For a very large range, iterate lazily with for (def i in lo..hi), which builds no list.
lists.range(0, 9, 3); # [0, 3, 6] - 9 excluded
lists.range(1, 9, 3); # [1, 4, 7] - 10 past 9, stop at 7
lists.range(10, 1, -3); # [10, 7, 4] - 1 excluded
lists.range(10, 0, -3); # [10, 7, 4, 1] - -2 past 0, stop at 1
lists.range(3, 0, -1); # [3, 2, 1] - counting downThe rule is always "emit while strictly before end", whether or not the step lands on it.
Value semantics
Every function copies its inputs; re-bind the result:
def xs as list of int init [1, 2, 3];
def ys as list of int init lists.push($xs, 4);
# $xs is still [1, 2, 3]; $ys is [1, 2, 3, 4]This is the same rule that makes $dst = $src; a copy.
See also: maps.md, index.md. len(xs) is a language built-in (no import needed).