11. Collections and text
11.1 list[T]#
list is a growable ordered collection with identity: two bindings of one list are the same list, is says so, and .copy() makes an independent shallow copy. Indexing is checked.
| Operation | Meaning |
|---|---|
length | a property, O(1) |
values[i], values[i] = x | get and set; i out of range traps; negative indexes count from the end |
values[a..<b], values[a..], values[..<b] | a new list of the elements; bounds checked |
append(x), insert(i, x), remove_at(i) -> T, pop() -> T, clear() | shape changes |
first, last | T? |
contains(x), index_of(x) -> int? | search, x equatable |
sort(), sorted(), reverse(), reversed() | in place and as a copy; elements ordered |
map(f), filter(f), join(separator) | with a function value; join on list[str] |
a + b | a new list of both |
copy() | a shallow copy |
11.2 map[K, V] and set[T]#
Maps and sets have identity, keep insertion order, and require equatable and hashable keys. m[key] is V?; m[key] = v inserts or replaces; m.remove(key) -> V?; key in m; m.keys(), m.values(), m.items() iterate. s.insert(x), s.remove(x) -> bool, x in s, s.union(t), s.intersection(t), s.difference(t). Both have length, clear(), copy().
11.3 str#
str is immutable UTF-8 with value semantics and content equality.
| Operation | Meaning |
|---|---|
length | scalars, O(n); byte_count is O(1) |
a + b, f"..." | concatenation and formatting |
text[a..<b] | a substring by scalar index; bounds checked |
for c in text | one-scalar strings |
contains, starts_with, ends_with, index_of -> int? | search |
split(separator) -> list[str], lines(), trim(), upper(), lower(), replace(a, b), repeat(n) | the common transforms |
bytes() | the UTF-8 as bytes |
split(separator) cuts at every occurrence of a non-empty separator, keeping empty pieces, so "a,,b".split(",") is ["a", "", "b"]; an empty separator traps. lines() cuts at "\n", drops a "\r" before it, and a trailing newline ends the last line rather than opening an empty one. trim() removes spaces, tabs and newlines at both ends; upper() and lower() map the ASCII letters; replace(a, b) replaces every non-overlapping occurrence left to right and traps on an empty a; repeat(n) traps on a negative n. Normalisation, grapheme segmentation, collation and locale are library operations.
11.4 bytes#
Immutable, with length, data[i] as an int 0 to 255, slicing, +, equality, and text(), which decodes UTF-8 and is str!, failing with the message invalid UTF-8. Bytes are what a Base package hands a Luce program when the data is not text; a Luce program does not compute on bytes, it passes them.