list
Functions for working with ordered, immutable lists (List(a)). Lists use
[...] literal syntax and support the range operator 1..5.
See also result / option for the return types of
find, find_map, first, last, get, and filter_map; stream for
channel-backed lazy pipelines over the same combinator names.
Summary
| Function | Signature | Description |
|---|---|---|
all | (List(a), Fn(a) -> Bool) -> Bool | True if predicate holds for every element |
any | (List(a), Fn(a) -> Bool) -> Bool | True if predicate holds for at least one element |
append | (List(a), a) -> List(a) | Add an element to the end |
chunks | (List(a), Int) -> List(List(a)) | Group elements into lists of n |
concat | (List(a), List(a)) -> List(a) | Concatenate two lists |
contains | (List(a), a) -> Bool where a: Equal | Check if element is in list |
drop | (List(a), Int) -> List(a) | Remove first n elements |
drop_while | (List(a), Fn(a) -> Bool) -> List(a) | Skip elements until f first rejects one |
each | (List(a), Fn(a) -> ()) -> () | Call function for each element (side effects) |
enumerate | (List(a)) -> List((Int, a)) | Pair each element with its index |
filter | (List(a), Fn(a) -> Bool) -> List(a) | Keep elements matching predicate |
filter_map | (List(a), Fn(a) -> Option(b)) -> List(b) | Filter and transform in one pass |
find | (List(a), Fn(a) -> Bool) -> Option(a) | First element matching predicate |
find_map | (List(a), Fn(a) -> Option(b)) -> Option(b) | The first Some that f returns; f is not called after it |
first | (List(a)) -> Option(a) | First element, or None |
flat_map | (List(a), Fn(a) -> List(b)) -> List(b) | Map then flatten |
flatten | (List(List(a))) -> List(a) | Flatten one level of nesting |
fold | (List(a), b, Fn(b, a) -> b) -> b | Reduce to a single value |
fold_until | (List(a), b, Fn(b, a) -> Step(b)) -> b | Fold with early termination |
get | (List(a), Int) -> Option(a) | Element at index, or None |
group_by | (List(a), Fn(a) -> b) -> Map(b, List(a)) where b: Hash | Group elements by key function |
index_of | (List(a), a) -> Option(Int) where a: Equal | Index of first matching element, or None |
intersperse | (List(a), a) -> List(a) | Insert separator between elements |
is_empty | (List(a)) -> Bool | True if the list has no elements |
last | (List(a)) -> Option(a) | Last element, or None |
length | (List(a)) -> Int | Number of elements |
map | (List(a), Fn(a) -> b) -> List(b) | Transform each element |
max_by | (List(a), Fn(a) -> b) -> Option(a) where b: Compare | Element with largest key, or None |
min_by | (List(a), Fn(a) -> b) -> Option(a) where b: Compare | Element with smallest key, or None |
prepend | (List(a), a) -> List(a) | Add an element to the front |
product | (List(a)) -> a where a: Number | Product of a list of numbers (a.from_int(1) on empty) |
remove_at | (List(a), Int) -> Option(List(a)) | The list without the element at index, or None if there is none |
reverse | (List(a)) -> List(a) | Reverse element order |
scan | (List(a), b, Fn(b, a) -> b) -> List(b) | Running fold: the accumulator after each element |
sequence | (List(m(a))) -> m(List(a)) where m: Applicative | One Applicative value of the list of the values: the first failure, if there is one |
set | (List(a), Int, a) -> Option(List(a)) | The list with the element at index replaced, or None if there is none |
sort | (List(a)) -> List(a) where a: Compare | Sort in natural order |
sort_by | (List(a), Fn(a) -> b) -> List(a) where b: Compare | Sort by key function |
sort_with | (List(a), Fn(a, a) -> Int) -> List(a) | Sort with a comparison function (below 0: less, 0: equal, above 0: greater); stable |
sum | (List(a)) -> a where a: Number | Sum of a list of numbers (a.from_int(0) on empty) |
tail | (List(a)) -> List(a) | All elements except the first |
take | (List(a), Int) -> List(a) | Keep first n elements |
take_while | (List(a), Fn(a) -> Bool) -> List(a) | Elements until f first rejects one |
traverse | (List(a), Fn(a) -> m(b)) -> m(List(b)) where m: Applicative | Call f on every element, then one Applicative value of the list of the results: the first failure, if there is one |
try_each | (List(a), Fn(a) -> Result((), e)) -> Result((), e) | Call f on each element in order up to the first Err, which is the result; else Ok(()) |
try_each_option | (List(a), Fn(a) -> Option(())) -> Option(()) | Call f on each element in order up to the first None, which is the result; else Some(()) |
unfold | (a, Fn(a) -> Option((b, a))) -> List(b) | Build a list from a seed |
unique | (List(a)) -> List(a) where a: Equal | Remove duplicates, preserving first occurrence |
unique_by | (List(a), Fn(a) -> b) -> List(a) where b: Hash | Keep the first element of each key |
zip | (List(a), List(b)) -> List((a, b)) | Pair elements from two lists |
Functor, Applicative and Monad
List(_) has the three built-in traits of type constructors (see
Functors): Functor.map is list.map,
Monad.flat_map is list.flat_map, List.pure(x) is [x], and
Applicative.map2(xs, ys, f) calls f on every pair, for each element
of xs each element of ys, in that order:
fn main() {
println(Functor.map([1, 2]) { x -> x * 10 }) -- [10, 20]
println(List.pure(1)) -- [1]
println(Applicative.map2([1, 2], ["a", "b"]) { n, s -> "{n}{s}" }) -- ["1a", "1b", "2a", "2b"]
}open in playgroundCode that knows it has a list writes list.map; the traits are for
generic code, and for list.traverse and list.sequence, which work
over any Applicative.
list.all
list.all(xs: List(a), f: Fn(a) -> Bool) -> Bool
Returns true if f returns true for every element. Short-circuits on the
first false.
import list
fn main() {
let all_even = list.all([2, 4, 6]) { x -> x % 2 == 0 }
println(all_even) -- true
}open in playgroundlist.any
list.any(xs: List(a), f: Fn(a) -> Bool) -> Bool
Returns true if f returns true for at least one element. Short-circuits on
the first true.
import list
fn main() {
let has_even = list.any([1, 3, 4]) { x -> x % 2 == 0 }
println(has_even) -- true
}open in playgroundlist.append
list.append(xs: List(a), elem: a) -> List(a)
Returns a new list with elem added at the end.
import list
fn main() {
let xs = [1, 2, 3] |> list.append(4)
println(xs) -- [1, 2, 3, 4]
}open in playgroundlist.chunks
list.chunks(xs: List(a), n: Int) -> List(List(a))
Splits the list into lists of n elements, in order; the last one is
shorter when the elements run out. An empty list gives []. An n below
1 is a runtime error (list.chunks: n must be positive), as for
stream.chunks.
import list
fn main() {
println(list.chunks([1, 2, 3, 4, 5], 2)) -- [[1, 2], [3, 4], [5]]
}open in playgroundlist.concat
list.concat(xs: List(a), ys: List(a)) -> List(a)
Concatenates two lists into a single list.
import list
fn main() {
let joined = list.concat([1, 2], [3, 4])
println(joined) -- [1, 2, 3, 4]
}open in playgroundlist.contains
list.contains(xs: List(a), elem: a) -> Bool where a: Equal
Returns true if elem is in the list (by value equality).
import list
fn main() {
println(list.contains([1, 2, 3], 2)) -- true
println(list.contains([1, 2, 3], 5)) -- false
}open in playgroundlist.drop
list.drop(xs: List(a), n: Int) -> List(a)
Returns the list without its first n elements. If n >= length, returns an
empty list; a negative n counts as 0 and returns the whole list.
import list
fn main() {
let tail = list.drop([1, 2, 3, 4, 5], 2)
println(tail) -- [3, 4, 5]
}open in playgroundlist.drop_while
list.drop_while(xs: List(a), f: Fn(a) -> Bool) -> List(a)
Returns the list from the first element for which f returns false:
the elements before it are dropped. f is not called after that element.
If f accepts every element, the result is empty.
import list
fn main() {
println(list.drop_while([1, 2, 5, 1]) { x -> x < 3 }) -- [5, 1]
println(list.drop_while([1, 2]) { x -> x < 3 }) -- []
}open in playgroundlist.each
list.each(xs: List(a), f: Fn(a) -> ()) -> ()
Calls f for every element in the list. Used for side effects. Returns unit.
import list
fn main() {
[1, 2, 3] |> list.each { x -> println(x) }
}open in playgroundlist.enumerate
list.enumerate(xs: List(a)) -> List((Int, a))
Returns a list of (index, element) tuples, with indices starting at 0.
import list
fn main() {
let pairs = list.enumerate(["a", "b", "c"])
-- [(0, "a"), (1, "b"), (2, "c")]
list.each(pairs) { (i, v) -> println("{i}: {v}") }
}open in playgroundlist.filter
list.filter(xs: List(a), f: Fn(a) -> Bool) -> List(a)
Returns a list containing only the elements for which f returns true.
import list
fn main() {
let evens = [1, 2, 3, 4, 5] |> list.filter { x -> x % 2 == 0 }
println(evens) -- [2, 4]
}open in playgroundlist.filter_map
list.filter_map(xs: List(a), f: Fn(a) -> Option(b)) -> List(b)
Applies f to each element. Keeps the inner values from Some results and
discards None results. Combines filtering and mapping in one pass.
import int
import list
fn main() {
let results = ["1", "abc", "3"]
|> list.filter_map { s ->
match int.parse(s) {
Ok(n) -> Some(n * 10)
Err(_) -> None
}
}
println(results) -- [10, 30]
}open in playgroundlist.find
list.find(xs: List(a), f: Fn(a) -> Bool) -> Option(a)
Returns Some(element) for the first element where f returns true, or
None if no match is found.
import list
fn main() {
let first_gt_2 = list.find([1, 2, 3, 4]) { x -> x > 2 }
println(first_gt_2) -- Some(3)
}open in playgroundlist.find_map
list.find_map(xs: List(a), f: Fn(a) -> Option(b)) -> Option(b)
Calls f on each element in order and returns the first Some it gives,
or None if it gives None for every element. f is not called on the
elements after that Some, so this is the lazy form of filter_map then
first.
import int
import list
import result
fn main() {
let first = list.find_map(["x", "12", "7"]) { s -> int.parse(s) |> result.to_option }
println(first) -- Some(12)
}open in playgroundlist.first
list.first(xs: List(a)) -> Option(a)
Returns Some(first_element) or None if the list is empty.
import list
fn main() {
println(list.first([1, 2, 3])) -- Some(1)
println(list.first([])) -- None
}open in playgroundlist.flat_map
list.flat_map(xs: List(a), f: Fn(a) -> List(b)) -> List(b)
Maps each element to a list, then flattens the results into a single list.
import list
fn main() {
let expanded = [1, 2, 3] |> list.flat_map { x -> [x, x * 10] }
println(expanded) -- [1, 10, 2, 20, 3, 30]
}open in playgroundlist.flatten
list.flatten(xs: List(List(a))) -> List(a)
Flattens one level of nesting.
import list
fn main() {
let flat = list.flatten([[1, 2], [3], [4, 5]])
println(flat) -- [1, 2, 3, 4, 5]
}open in playgroundlist.fold
list.fold(xs: List(a), init: b, f: Fn(b, a) -> b) -> b
Reduces a list to a single value. Starts with init, then calls f(acc, elem)
for each element.
import list
fn main() {
let sum = [1, 2, 3] |> list.fold(0) { acc, x -> acc + x }
println(sum) -- 6
}open in playgroundlist.fold_until
list.fold_until(xs: List(a), init: b, f: Fn(b, a) -> Step(b)) -> b
Like fold, but the callback returns Continue(acc) to keep going or
Stop(value) to terminate early. Continue and Stop are the prelude’s
(the variants of Step, which channel.fold_until and stream.fold_until
take too): they need no import.
import list
fn main() {
-- Sum until we exceed 5
let partial_sum = list.fold_until([1, 2, 3, 4, 5], 0) { acc, x ->
let next = acc + x
match {
next > 5 -> Stop(acc)
_ -> Continue(next)
}
}
println(partial_sum) -- 3
}open in playgroundlist.get
list.get(xs: List(a), i: Int) -> Option(a)
Returns Some(element) at the given index, or None if there is no such
position: an index past the end, or a negative one (use list.last for end
access).
import list
fn main() {
let xs = [10, 20, 30]
println(list.get(xs, 1)) -- Some(20)
println(list.get(xs, 10)) -- None
println(list.get(xs, -1)) -- None
}open in playgroundlist.group_by
list.group_by(xs: List(a), f: Fn(a) -> b) -> Map(b, List(a)) where b: Hash
Groups elements by the result of applying f. Returns a map from keys to lists
of elements that produced that key.
import list
fn main() {
let groups = [1, 2, 3, 4, 5, 6] |> list.group_by { x -> x % 2 }
println(groups) -- #{ 0: [2, 4, 6], 1: [1, 3, 5] }
}open in playgroundlist.index_of
list.index_of(xs: List(a), target: a) -> Option(Int) where a: Equal
Returns Some(index) of the first element equal to target (by value
equality), or None if no element matches.
import list
fn main() {
println(list.index_of([10, 20, 30, 20], 20)) -- Some(1)
println(list.index_of([10, 20, 30], 99)) -- None
}open in playgroundlist.intersperse
list.intersperse(xs: List(a), sep: a) -> List(a)
Returns a new list with sep inserted between consecutive elements. Empty and
single-element inputs are returned unchanged.
import list
fn main() {
println(list.intersperse([1, 2, 3], 0)) -- [1, 0, 2, 0, 3]
println(list.intersperse([42], 0)) -- [42]
println(list.intersperse([], 0)) -- []
}open in playgroundlist.is_empty
list.is_empty(xs: List(a)) -> Bool
Returns true if the list has no elements.
import list
fn main() {
println(list.is_empty([])) -- true
println(list.is_empty([1, 2])) -- false
}open in playgroundlist.last
list.last(xs: List(a)) -> Option(a)
Returns Some(last_element) or None if the list is empty.
import list
fn main() {
println(list.last([1, 2, 3])) -- Some(3)
println(list.last([])) -- None
}open in playgroundlist.length
list.length(xs: List(a)) -> Int
Returns the number of elements in the list.
import list
fn main() {
println(list.length([1, 2, 3])) -- 3
println(list.length([])) -- 0
}open in playgroundlist.map
list.map(xs: List(a), f: Fn(a) -> b) -> List(b)
Returns a new list with f applied to each element.
import list
fn main() {
let doubled = [1, 2, 3] |> list.map { x -> x * 2 }
println(doubled) -- [2, 4, 6]
}open in playgroundlist.max_by
list.max_by(xs: List(a), key: Fn(a) -> b) -> Option(a) where b: Compare
Returns Some(element) whose key result is largest, or None if the list
is empty. On ties, returns the first element with the maximum key. Requires
b to support comparison (numbers, strings, etc.).
import list
import string
fn main() {
let words = ["fig", "banana", "apple"]
let longest = list.max_by(words) { w -> string.length(w) }
println(longest) -- Some("banana")
println(list.max_by([]) { x -> x }) -- None
}open in playgroundlist.min_by
list.min_by(xs: List(a), key: Fn(a) -> b) -> Option(a) where b: Compare
Returns Some(element) whose key result is smallest, or None if the list
is empty. On ties, returns the first element with the minimum key. Requires
b to support comparison (numbers, strings, etc.).
import list
import string
fn main() {
let words = ["banana", "fig", "apple"]
let shortest = list.min_by(words) { w -> string.length(w) }
println(shortest) -- Some("fig")
println(list.min_by([]) { x -> x }) -- None
}open in playgroundlist.prepend
list.prepend(xs: List(a), elem: a) -> List(a)
Returns a new list with elem added at the front.
import list
fn main() {
let xs = [2, 3] |> list.prepend(1)
println(xs) -- [1, 2, 3]
}open in playgroundlist.product
list.product(xs: List(a)) -> a where a: Number
Returns the product of all elements, of a list of Ints or of Floats.
Returns a.from_int(1) on an empty list: 1, or 1.0. Overflow is a
runtime error: an Int product beyond the range of Int, a Float
product too large for a Float. The product of a list of Ints that has
a 0 in it is 0, whatever the product of the other elements is.
import list
fn main() {
println(list.product([1, 2, 3, 4])) -- 24
println(list.product([1.5, 2.0, 4.0])) -- 12.0
println(list.product(-100..100)) -- 0
let none: List(Float) = []
println(list.product(none)) -- 1.0
}open in playgroundlist.remove_at
list.remove_at(xs: List(a), index: Int) -> Option(List(a))
Returns Some of a new list with the element at index removed, or None if
the list has no such position (an index past the end, or a negative one), as
list.get and list.set do.
import list
fn main() {
println(list.remove_at([10, 20, 30, 40], 1)) -- Some([10, 30, 40])
println(list.remove_at([1, 2], 5)) -- None
}open in playgroundlist.reverse
list.reverse(xs: List(a)) -> List(a)
Returns a new list with elements in reverse order.
import list
fn main() {
println(list.reverse([1, 2, 3])) -- [3, 2, 1]
}open in playgroundlist.sequence
list.sequence(xs: List(m(a))) -> m(List(a)) where m: Applicative
Turns a list of values of an Applicative m (Option, Result, List,
or a type of your own) into one value of m that holds the list: the first
failure (None, Err) if there is one. Of lists, it gives every
combination. It is list.traverse with each element as it is.
import list
fn main() {
println(list.sequence([Some(1), Some(2)])) -- Some([1, 2])
println(list.sequence([Some(1), None])) -- None
println(list.sequence([[1, 2], [3]])) -- [[1, 3], [2, 3]]
}open in playgroundlist.set
list.set(xs: List(a), index: Int, value: a) -> Option(List(a))
Returns Some of a new list with the element at index replaced by value,
or None if the list has no such position (an index past the end, or a
negative one).
import list
fn main() {
println(list.set([10, 20, 30], 1, 99)) -- Some([10, 99, 30])
println(list.set([10, 20, 30], 3, 99)) -- None
}open in playgroundlist.sort
list.sort(xs: List(a)) -> List(a) where a: Compare
Returns a new list sorted in natural (ascending) order. For the descending order, reverse the sorted list:
import list
fn main() {
println(list.sort([3, 1, 2])) -- [1, 2, 3]
println(list.sort([3, 1, 2]) |> list.reverse) -- [3, 2, 1]
}open in playgroundlist.scan
list.scan(xs: List(a), init: b, f: Fn(b, a) -> b) -> List(b)
Like fold, but returns every accumulator on the way rather than just the
final one: the accumulator after applying f to each element, one for each
element, so the result is as long as xs. init itself is not in it, as
stream.scan does not send it.
import list
fn main() {
-- Prefix sums: [1, 3, 6, 10]
let sums = list.scan([1, 2, 3, 4], 0) { acc, x -> acc + x }
println(sums)
println(list.scan([], 0) { acc, x -> acc + x }) -- []
}open in playgroundlist.sort_by
list.sort_by(xs: List(a), key: Fn(a) -> b) -> List(a) where b: Compare
Returns a new list sorted by the result of applying the key function to each element. The sort is stable: elements with equal keys keep their order.
A tuple key sorts by its first part, then by the next where the first
parts are equal, and so on. A part of an Int or Float key sorts
descending when it is negated; for the descending order of a key that
cannot be negated, use list.sort_with (or |> list.reverse on the
sorted list, which also reverses the order of equal keys).
import list
import string
type Player {
name: String,
score: Int,
}
fn main() {
let words = ["banana", "fig", "apple"]
let sorted = words |> list.sort_by { w -> string.length(w) }
println(sorted) -- ["fig", "apple", "banana"]
let players = [
Player { name: "Bo", score: 7 },
Player { name: "Al", score: 9 },
Player { name: "Cy", score: 7 },
]
-- By score, highest first, then by name.
let ranked = players |> list.sort_by { p -> (-p.score, p.name) }
println(list.map(ranked) { p -> p.name }) -- ["Al", "Bo", "Cy"]
}open in playgroundlist.sort_with
list.sort_with(xs: List(a), cmp: Fn(a, a) -> Int) -> List(a)
Returns a new list sorted by the comparison function: cmp(a, b) is below
0 when a comes before b, 0 when the two are equal, and above 0 when a
comes after b. The sort is stable: equal elements keep their order.
Compare.compare(b, a) sorts descending, by any key that has Compare.
import list
fn main() {
println(list.sort_with([3, 1, 2]) { a, b -> Compare.compare(b, a) }) -- [3, 2, 1]
-- By the first of each pair only: (1, b) stays before (1, a).
let pairs = [(2, "c"), (1, "b"), (1, "a")]
println(list.sort_with(pairs) { (x, _), (y, _) -> Compare.compare(x, y) }) -- [(1, "b"), (1, "a"), (2, "c")]
}open in playgroundlist.sum
list.sum(xs: List(a)) -> a where a: Number
Returns the sum of all elements, of a list of Ints or of Floats.
Returns a.from_int(0) on an empty list: 0, or 0.0. Overflow is a
runtime error: an Int sum beyond the range of Int, a Float sum too
large for a Float, counted from the first element on: a sum on the way
that is too large is one too, even where the elements after it would
bring the sum back ([1.0e308, 1.0e308, -1.0e308]).
import list
fn main() {
println(list.sum([1, 2, 3, 4])) -- 10
println(list.sum([0.5, 1.5, 2.0])) -- 4.0
let none: List(Int) = []
println(list.sum(none)) -- 0
}open in playgroundlist.tail
list.tail(xs: List(a)) -> List(a)
Returns all elements except the first. Returns an empty list if the input is empty.
import list
fn main() {
println(list.tail([1, 2, 3])) -- [2, 3]
println(list.tail([])) -- []
}open in playgroundlist.take
list.take(xs: List(a), n: Int) -> List(a)
Returns the first n elements. If n >= length, returns the whole list; a
negative n counts as 0 and returns an empty list.
import list
fn main() {
println(list.take([1, 2, 3, 4, 5], 3)) -- [1, 2, 3]
}open in playgroundlist.take_while
list.take_while(xs: List(a), f: Fn(a) -> Bool) -> List(a)
Returns the elements up to the first one for which f returns false,
without it. f is not called after that element. If f accepts every
element, the result is the whole list.
import list
fn main() {
println(list.take_while([1, 2, 5, 1]) { x -> x < 3 }) -- [1, 2]
println(list.take_while([]) { x -> x < 3 }) -- []
}open in playgroundlist.traverse
list.traverse(xs: List(a), f: Fn(a) -> m(b)) -> m(List(b)) where m: Applicative
Calls f on every element, left to right, then gives one value of the
Applicative m that holds the list of the results: the first failure
(None, Err) if there is one. f is called on every element, also after
one has failed; for steps that must stop at the first failure, use
list.try_each. Of lists, it gives every combination.
import int
import list
fn main() {
println(["1", "2"] |> list.traverse(int.parse)) -- Ok([1, 2])
println(["1", "x"] |> list.traverse(int.parse)) -- Err(invalid digit at byte 0)
println(list.traverse([1, 2]) { x -> [x, -x] }) -- [[1, 2], [1, -2], [-1, 2], [-1, -2]]
}open in playgroundlist.try_each
list.try_each(xs: List(a), f: Fn(a) -> Result((), e)) -> Result((), e)
Calls f on each element, left to right, up to the first that gives an
Err: that Err is the result, and f is not called on the elements
after it. When every call gives Ok(()), the result is Ok(()). It is
list.each for steps that can fail, such as writing files: with ?,
the first failure ends the function too. Above, check prints read 1
and read 2 for the first list, and only read 1 for the second.
import int
import list
fn check(s: String) -> Result((), int.IntError) {
let _ = int.parse(s)?
println("read {s}")
Ok(())
}
fn main() {
println(list.try_each(["1", "2"], check)) -- Ok(())
println(list.try_each(["1", "x", "3"], check)) -- Err(invalid digit at byte 0)
}open in playgroundlist.try_each_option
list.try_each_option(xs: List(a), f: Fn(a) -> Option(())) -> Option(())
list.try_each for a function that gives an Option: calls f on each
element, left to right, up to the first that gives None, which is the
result. When every call gives Some(()), the result is Some(()).
import list
import map
import option
fn main() {
let stock = #{ "pen": 2, "ink": 0 }
let take = { item -> map.get(stock, item) |> option.map { _ -> println("took {item}") } }
println(list.try_each_option(["pen", "cap", "ink"], take)) -- None
}open in playgroundlist.unfold
list.unfold(seed: a, f: Fn(a) -> Option((b, a))) -> List(b)
Builds a list from a seed value. The function returns Some((element, next_seed))
to emit an element and continue, or None to stop.
import list
fn main() {
let countdown = list.unfold(5) { n ->
match {
n <= 0 -> None
_ -> Some((n, n - 1))
}
}
println(countdown) -- [5, 4, 3, 2, 1]
}open in playgroundlist.unique
list.unique(xs: List(a)) -> List(a) where a: Equal
Removes duplicate elements, preserving the order of first occurrences.
import list
fn main() {
println(list.unique([1, 2, 1, 3, 2])) -- [1, 2, 3]
}open in playgroundlist.unique_by
list.unique_by(xs: List(a), key: Fn(a) -> b) -> List(a) where b: Hash
Keeps the first element of each key, in the order of the list: an element whose key an earlier element has is removed.
import list
import string
fn main() {
let words = ["apple", "avocado", "banana", "blueberry", "cherry"]
println(list.unique_by(words) { w -> string.slice(w, 0, 1) }) -- ["apple", "banana", "cherry"]
}open in playgroundlist.zip
list.zip(xs: List(a), ys: List(b)) -> List((a, b))
Pairs up elements from two lists. Stops at the shorter list.
import list
fn main() {
let pairs = list.zip([1, 2, 3], ["a", "b", "c"])
println(pairs) -- [(1, "a"), (2, "b"), (3, "c")]
}open in playground