Collections
Nomi has four collection types: List<T>,
Vector<T>, Map<K, V>
and Set<T>. It also has
Range<T>, the values between a start and an
end.
A collection never changes. An operation that adds, removes or replaces something gives you a new collection, and the original stays as it was. Collections that work this way are called persistent.
Brackets hold a list, a vector or a set. [1, 2] is a vector where a vector
is expected and a set where a set is expected. Where nothing expects a
collection, it is a list. To make a vector or a set there, name it:
Vector[1, 2], Set[1, 2]. Braces hold a map, {"a" => 1}. Parentheses
with a comma inside hold a tuple, (1, "a"), a fixed group of values that
Tuples covers.
A function that works on a collection takes it as its first argument. That is what lets you chain calls with pipes.
Every collection is an Iter: something you
can walk through one value at a time. So is a range of whole numbers or
codepoints, and so is a String, which gives one character at a time.
The general operations live on Iter and work on all of them: Iter.map,
Iter.filter, Iter.take, Iter.reduce, Iter.sum, Iter.count,
Iter.min, Iter.max, Iter.mean and more. Each collection type keeps
only the operations specific to it, such as Map.get or List.first.
Iter.min, Iter.max and Iter.mean return None for an empty source,
and the mean of Ints is a Float: Iter.mean([1, 2]) is Some(1.5).
import std::io
fn main()
result =
Range.naturals()
|> Iter.map(fn n ->
io.print("squaring ${n}")
n * n
end)
|> Iter.filter(&(&1 > 10))
|> Iter.take(2)
|> Iter.to_list()
dbg result
endsquaring 0
squaring 1
squaring 2
squaring 3
squaring 4
squaring 5
dbg line 14: result = [16, 25]
Range.naturals() counts 0, 1, 2 and on without end. The program still
finishes, and it squares only 0 through 5.
That is because Iter.map, Iter.filter and Iter.take are lazy. Each one
describes a step but runs nothing, and no list is built between steps. The work
starts when a final call asks for values. Here that is Iter.to_list. Others
are Iter.to_vector, Iter.to_set, Iter.to_map, String.join,
Iter.reduce, Iter.sum, Iter.count and Iter.each.
Each value goes through every step before the next value starts. The work stops
as soon as the final call has what it needs. Iter.take(2) has its two values
once 25 arrives, so nothing after 5 is squared.
Without the Iter.take(2), the program would never finish, so Nomi doesn’t
compile it. The compiler can see that Range.naturals() never ends, that
Iter.map and Iter.filter don’t change that, and that Iter.to_list
needs every value:
error:
Sometimes the compiler can’t see where the values come from, for example
when an endless iterator is passed in as a parameter. Then the program stops
with a similar message at the Iter.to_list line, before it squares
anything, instead of running until it runs out of memory. An iterator says
that it never ends through
Iter.is_infinite.
fn main()
xs = [1, 2, 3, 4, 5]
xs
|> Iter.filter(&(&1 > 2))
|> Iter.map(fn n -> n * n)
|> Iter.sum()
|> dbg
enddbg line 8:
xs
|> Iter.filter(&(&1 > 2))
|> Iter.map(fn n -> n * n)
|> Iter.sum()
= 50
You write a list as [a, b, c]. The List type
has the functions specific to lists, such as concat, first and tail.
To transform a list, use the Iter functions, as above. When you want a list
back at the end, finish with Iter.to_list().
[x, ..xs] is a new list with x in front of xs. Spreads covers
this.
A function that needs at least one element takes a
NonEmptyList, whose
NonEmptyList.first and NonEmptyList.max return the element rather than a
Maybe; NonEmptyVector, NonEmptyMap and NonEmptySet do the same for
the other collections. List.first on a NonEmptyList is still a Maybe,
and the editor hints NonEmptyList.first there.
Vectors
Section titled “Vectors”fn main()
names =
Vector["Ada", "Grace"]
|> Vector.push("Katherine")
dbg names
dbg Vector.length(names)
dbg Vector.get(names, 1)
dbg Vector.get(names, 5)
dbg Vector.get(names, 1)!
dbg names + ["Dorothy"]
enddbg line 6: names = Vector["Ada", "Grace", "Katherine"]
dbg line 7: Vector.length(names) = 3
dbg line 8: Vector.get(names, 1) = Some("Grace")
dbg line 9: Vector.get(names, 5) = None
dbg line 10: Vector.get(names, 1)! = "Grace"
dbg line 11: names + ["Dorothy"] = Vector["Ada", "Grace", "Katherine", "Dorothy"]
You write a vector as [a, b, c] wherever one is expected: beside another
vector, as in names + ["Dorothy"], or for a binding, parameter or field of
type Vector<String>. Where nothing expects one, Vector[a, b, c] names it.
Iter.to_vector builds one from any Iter.
A vector is a sequence you can read by position. Use a vector when you look items up by index or add them at the end. Use a list when you add items at the front.
Indexes start at 0.
Vector.get returns a
Maybe: Some(item) when the index is inside the
vector, None when it is not. Use it when the index comes from data.
Vector.get(names, 1)!, with a
postfix !, returns the item
itself and stops the program when the index is outside, so use it when your
code guarantees the index.
Vector.set replaces the item at an index and
returns a Maybe the same way, so Vector.set(names, 1, "Bo")! is the new
vector when your code guarantees the index.
xs + ys joins two lists, or two vectors.
List.concat and
Vector.concat do the same thing by name.
A case can take a vector apart from either end, as
Pattern Matching shows.
fn main()
config = {"host" => "localhost", "port" => "8080"}
dbg Map.size(config)
dbg Map.get(config, "host")
dbg Map.get(config, "user")
enddbg line 4: Map.size(config) = 2
dbg line 5: Map.get(config, "host") = Some("localhost")
dbg line 6: Map.get(config, "user") = None
You write a map as {"key" => value, ...}, and the empty map as {}.
Map.get also returns a Maybe: Some(value)
when the key is there and None when it is not.
Pattern Matching shows how to get the value out.
a + b merges two maps. When both have the same key, the value from b wins.
Map.merge does the same thing by name. To add or
replace a few entries, use a spread, shown below.
Fine print
- A key can be any value with equality, at any depth: a tuple, a list, a
struct, a distinct value. Keys match by
==. - A function, an
Iterand a handle to running state (aTask, aSender) have no equality, so they can’t be keys or set elements:`Iter<Int>` cannot be a Map key: an Iter has no equality or hashing. - Map keys in a literal are expressions:
{key => 1}reads the bindingkey. A string key is quoted. - A key of a type with its own
impl Equatablematches through it. Write a matchingimpl Hashabletoo, or all its keys share one bucket.
Spec: Hashing and keys, Literal forms.
fn main()
s = Set[1, 2, 3]
dbg Set.size(s)
dbg 2 in s
dbg not 9 in s
dbg s + [4, 5]
dbg s - [1]
enddbg line 4: Set.size(s) = 3
dbg line 5: 2 in s = True
dbg line 6: not 9 in s = True
dbg line 7: s + [4, 5] = Set[1, 2, 3, 4, 5]
dbg line 8: s - [1] = Set[2, 3]
You write a set as [a, b, c] wherever one is expected, as beside s
above or for a binding, parameter or field of type Set<Int>, and as
Set[a, b, c] where nothing expects one, as for s. A set holds each value
once: Iter.to_set builds one from any Iter,
so Iter.to_set([1, 2, 3, 2, 1]) has three values. It keeps them in the order
each one first appeared.
x in c tests whether a collection holds a value, for a list, vector, set,
range, string and map alike (a map holds its keys): it is
Contains.contains(c, x) written as an operator.
If you write the same value twice in a set literal, as in Set[1, 2, 1], the
compiler reports an error. It does the same for a key written twice in a map
literal.
An empty set takes its element type from where it is used. On a binding with no
other use to go by, write the type: empty: Set<Int> = [].
a + b is every value in either set, and a - b is the values of a that are
not in b. Set.union and
Set.difference do the same by name. To add
or remove one value, use Set.insert and
Set.remove.
A case can ask whether a set holds certain values, as
Pattern Matching shows.
Fine print
- The duplicate check covers constants only: literals,
TrueandFalse, variants without a payload and tuples of those.255and0xFFare the same key, and so are0.0and-0.0. - Keys equal only at run time are allowed. The later value wins and the key
keeps the earlier position: with
x = 1andy = 1,{x => "a", 2 => "c", y => "b"}is{1 => "b", 2 => "c"}. [1, 2]is a list wherever nothing expects a vector or a set.List[1, 2]andMap{"a" => 1}are allowed too, and never needed.
Spec: Repeated keys, Literal forms.
Spreads
Section titled “Spreads”A spread, written .., builds a new collection from an existing one:
fn main()
xs = ["Bo"]
v = Vector["Bo"]
s = Set["red"]
m = {"host" => "localhost", "port" => "8080"}
dbg ["Ada", ..xs]
dbg [..v, "Cy"]
dbg ["Ada", ..v]
dbg [..s, "blue"]
dbg {..m, "port" => "9090", "user" => "ada"}
enddbg line 7: ["Ada", ..xs] = ["Ada", "Bo"]
dbg line 8: [..v, "Cy"] = Vector["Bo", "Cy"]
dbg line 9: ["Ada", ..v] = Vector["Ada", "Bo"]
dbg line 10: [..s, "blue"] = Set["red", "blue"]
dbg line 11: {..m, "port" => "9090", "user" => "ada"} = {"host" => "localhost", "port" => "9090", "user" => "ada"}
Where nothing expects a collection, a literal with a spread is the
collection its spread is, so [..v, "Cy"] is a vector and [..s, "blue"]
a set. A spread can go anywhere in the literal, and a literal can have several:
[..xs, "Cy", ..ys]. In a map a later key wins, so {..m, "port" => "9090"}
replaces m’s port, and {"port" => "9090", ..m} keeps it. In a list,
vector or set, a spread can be any Iter, such as [0, ..xs |> Iter.map(f)].
In a map you are updating, a .. with nothing after it means the value
already under that key:
fn main()
scores = {"ada" => [3]}
dbg {..scores, "ada" => [5, ..], "bob" => [1, ..]}
enddbg line 3: {..scores, "ada" => [5, ..], "bob" => [1, ..]} = {"ada" => [5, 3], "bob" => [1]}
"ada" => [5, ..] puts 5 in front of Ada’s scores. Without the .., the new
list would replace the old one. For a key that is not there yet, .. starts
from an empty collection, so "bob" gets only [1]. A struct field updates
the same way (Updating a struct).
Fine print
- A list, vector or set spread can be any
Iterof the elements, including aMaybe, which adds zero or one:[1, ..Some(2), ..None]is[1, 2]. - A map spread must be a map of the literal’s type. A later key replaces an earlier one’s value and keeps its position.
- A literal holding one spread of its own type and nothing else is an
error:
[..s]asks you to writes. - A struct literal takes one spread, and it comes first. That is a struct update.
- A distinct type over a
collection writes its name before its literal, and that form takes no
spread: with
type Kvs Map<String, Int>,Kvs{..base, "a" => 1}is an error, since the base already carries the type.
Spec: Spreads.
Ranges
Section titled “Ranges”1..5 is a range that leaves out its end: 1, 2, 3 and 4. 1..=5 includes its
end. The type of the start and end decides the type of the range: 1..5 is a
Range<Int>, "a".."m" is a Range<String> and 0.0..=1.0 is a
Range<Float>.
Any range can tell you whether a value falls inside it. Some ranges can also be walked through one value at a time, like a list. A range of whole numbers can, because each number has a next one:
fn main()
dbg Iter.to_list(1..5)
dbg Iter.to_list(1..=5)
enddbg line 2: Iter.to_list(1..5) = [1, 2, 3, 4]
dbg line 3: Iter.to_list(1..=5) = [1, 2, 3, 4, 5]
So does a range of Codepoint values, written
with codepoint literals such as 'a':
fn main()
'a'..='d'
|> Iter.map(Codepoint.to_string)
|> Iter.to_list()
|> dbg
enddbg line 5:
'a'..='d'
|> Iter.map(Codepoint.to_string)
|> Iter.to_list()
= ["a", "b", "c", "d"]
A range of strings or floats cannot be walked through, because there is no
single next value. There is no obvious string that comes right after "a".
You can still ask whether a value is inside it:
fn main()
dbg Range.contains("a".."m", "h")
dbg Range.contains(0.0..=1.0, 1.0)
enddbg line 2: Range.contains("a".."m", "h") = True
dbg line 3: Range.contains(0.0..=1.0, 1.0) = True
Range.step_by walks through a range in
steps of the size you give. It works on a range of any
Steppable type. Below, that type is Decimal.
Like Iter.map, Range.step_by is lazy:
fn main()
1.0d..=1.3d
|> Range.step_by(0.1d)
|> Iter.to_list()
|> dbg
enddbg line 5:
1.0d..=1.3d
|> Range.step_by(0.1d)
|> Iter.to_list()
= [1.0d, 1.1d, 1.2d, 1.3d]
A range whose end is below its start, such as 5..=1, is empty. To count
down, step by a negative amount: Range.step_by(5..=1, -1) gives 5, 4, 3,
2 and 1.
A function that needs a range with something in it takes a subtype of
Range: Int.clamp(n, 0..=10) takes a ClosedRange and
Generator.int(1..=6) a BoundedRange, so Int.clamp(n, 10..=0) is an
error when the program is compiled. A range computed when it runs goes
through ClosedRange.try_from or BoundedRange.try_from.
Fine print
- Both bounds are required:
..5and5..are not ranges, since..alone is a spread. An endless range comes fromRange.from(n)orRange.naturals(). ..binds looser than arithmetic and tighter than comparison:1 + 2..5 + 1is3..6.x in rtests membership for any range, including one you can’t walk through:"h" in "a".."m".- Both bounds have one
Comparabletype.1..2.0is a type error.
Spec: Range literals.
See it in action
Section titled “See it in action”Every example that uses Collections
The next chapter, Iteration & Loops, covers
Iter.loop for loops that carry state. It also
covers what break, continue and return do inside the functions you pass
to Iter.map and the others.