- Bit operators & | ^ ~ << >> and their op= forms (Go precedence),
plus hex, binary and octal literals (0xff, 0b1010, 0o755)
- defer stmt / defer { ... }: runs when the block ends, last first,
also on return, ?, break and continue
- List methods insert, remove, clear, contains, index_of, reverse,
sort and sort_by (stable merge sort)
- rand module: int(a, b), float(), seed(n)
- assert(cond[, msg]) and `rex test`, which runs each test_ function
in its own process
- rex.toml marks a project's top folder: imports count from there
- Docs, formatter, LSP completions and editor grammars updated
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
259 lines
5.4 KiB
Markdown
259 lines
5.4 KiB
Markdown
# 5. Lists and maps
|
|
|
|
## Lists: `[]T`
|
|
|
|
An ordered, growable sequence.
|
|
|
|
```rex
|
|
func main() {
|
|
var nums = [10, 20, 30]
|
|
nums.push(40)
|
|
nums[0] = 11
|
|
print(nums, nums.len(), nums[1])
|
|
print(nums.pop(), nums)
|
|
print(nums[1..3]) // a copy of part of the list
|
|
|
|
var names: []string // empty list: write the type
|
|
names.push("ann")
|
|
print(names)
|
|
|
|
var total = 0
|
|
for n in nums { total += n }
|
|
print(total)
|
|
}
|
|
```
|
|
```text
|
|
[11, 20, 30, 40] 4 20
|
|
40 [11, 20, 30]
|
|
[20, 30]
|
|
[ann]
|
|
61
|
|
```
|
|
|
|
### More list methods
|
|
|
|
```rex
|
|
func main() {
|
|
var xs = [5, 3, 9]
|
|
xs.insert(0, 7) // put 7 at position 0; the rest move up
|
|
print(xs)
|
|
print(xs.remove(1), xs) // take out the item at position 1 and get it
|
|
print(xs.contains(9), xs.index_of(9), xs.index_of(4))
|
|
xs.sort()
|
|
print(xs)
|
|
xs.reverse()
|
|
print(xs)
|
|
xs.clear()
|
|
print(xs, xs.len())
|
|
}
|
|
```
|
|
```text
|
|
[7, 5, 3, 9]
|
|
5 [7, 3, 9]
|
|
true 2 -1
|
|
[3, 7, 9]
|
|
[9, 7, 3]
|
|
[] 0
|
|
```
|
|
|
|
| | |
|
|
|--|--|
|
|
| `xs.push(v)` / `xs.pop()` | add at the end / take the last one |
|
|
| `xs.insert(i, v)` | put `v` at position `i` (`i` may be `xs.len()`, the end) |
|
|
| `xs.remove(i)` | take out the item at `i` and give it back |
|
|
| `xs.clear()` | remove everything |
|
|
| `xs.contains(v)` / `xs.index_of(v)` | is it there? / its first position, or `-1` |
|
|
| `xs.reverse()` | turn the list around |
|
|
| `xs.sort()` | smallest first (numbers, `char`s, strings A-Z) |
|
|
| `xs.sort_by(less)` | your own order: `less(a, b)` says whether `a` goes before `b` |
|
|
|
|
`contains` and `index_of` work where `==` does (numbers, strings, `char`, `bool`, enums
|
|
without data). For structs, sort with `sort_by`:
|
|
|
|
```rex
|
|
struct Player {
|
|
name: string
|
|
score: int
|
|
}
|
|
|
|
func main() {
|
|
var ps = [Player{"ann", 30}, Player{"bob", 50}, Player{"cy", 30}]
|
|
ps.sort_by((a, b) => a.score > b.score) // highest first
|
|
for p in ps {
|
|
print(p.name, p.score)
|
|
}
|
|
}
|
|
```
|
|
```text
|
|
bob 50
|
|
ann 30
|
|
cy 30
|
|
```
|
|
|
|
Sorting is **stable**: items that compare equal keep their order (ann stays before cy).
|
|
|
|
Facts:
|
|
- An empty list needs a type: `var xs: []int`.
|
|
- Going outside the list (`nums[9]`) or popping an empty list stops the program with a message.
|
|
- **Lists are values.** `var b = a` copies the list. Changing `b` leaves `a` alone.
|
|
|
|
```rex
|
|
func main() {
|
|
var a = [1, 2, 3]
|
|
var b = a
|
|
b.push(4)
|
|
print(a, b)
|
|
}
|
|
```
|
|
```text
|
|
[1, 2, 3] [1, 2, 3, 4]
|
|
```
|
|
|
|
## Maps: `map[K, V]`
|
|
|
|
A map finds a value by a **key** instead of a position, like a phone book.
|
|
|
|
```rex
|
|
func main() {
|
|
var ages = {"alice": 30, "bob": 25}
|
|
ages["carol"] = 41 // add a new entry
|
|
ages["bob"] = 26 // change an existing one
|
|
print(ages["bob"], ages.len())
|
|
print(ages)
|
|
}
|
|
```
|
|
```text
|
|
26 3
|
|
{alice: 30, bob: 26, carol: 41}
|
|
```
|
|
|
|
### Making a map
|
|
|
|
```rex
|
|
func main() {
|
|
var a = {"x": 1, "y": 2} // types are guessed from the entries
|
|
var b: map[string, int] = {} // empty: the type comes from the variable
|
|
var c = map[int, string]{} // empty: the type is written on the right
|
|
b["z"] = 26
|
|
c[7] = "seven"
|
|
print(a, b, c)
|
|
}
|
|
```
|
|
```text
|
|
{x: 1, y: 2} {z: 26} {7: seven}
|
|
```
|
|
|
|
An empty `{}` always needs a type from one of those two places.
|
|
|
|
### Keys
|
|
|
|
A key can be an `int` (or another whole-number type), a `string` or a `bool`.
|
|
The value can be anything: numbers, strings, lists, structs, even other maps.
|
|
|
|
### Reading
|
|
|
|
| Code | Result |
|
|
|------|--------|
|
|
| `m[k]` | the value; **stops the program** if `k` is missing |
|
|
| `m.has(k)` | `true` or `false` |
|
|
| `m.get(k)` | the value or `nil` (type `V?`, see [Errors and nil](07-errors-and-nil.md)) |
|
|
| `m.get_or(k, d)` | the value, or `d` if `k` is missing |
|
|
| `m.len()` | number of entries |
|
|
| `m.keys()` | a list of the keys |
|
|
| `m.values()` | a list of the values |
|
|
|
|
```rex
|
|
func main() {
|
|
var stock = {"apple": 3, "pear": 0}
|
|
print(stock.has("apple"), stock.has("fig"))
|
|
print(stock.get("apple"), stock.get("fig"))
|
|
print(stock.get_or("fig", -1))
|
|
print(stock.keys(), stock.values())
|
|
}
|
|
```
|
|
```text
|
|
true false
|
|
3 nil
|
|
-1
|
|
[apple, pear] [3, 0]
|
|
```
|
|
|
|
### Changing
|
|
|
|
`m[k] = v` adds or replaces. `m.remove(k)` deletes (and does nothing if the key is missing).
|
|
|
|
```rex
|
|
func main() {
|
|
var m = {"a": 1, "b": 2}
|
|
m["c"] = 3
|
|
m.remove("a")
|
|
print(m)
|
|
}
|
|
```
|
|
```text
|
|
{b: 2, c: 3}
|
|
```
|
|
|
|
### Counting: `+=` starts from zero
|
|
|
|
The most common map job is counting. `m[k] += 1` on a key that isn't there yet starts from
|
|
zero, so you don't have to check first.
|
|
|
|
```rex
|
|
func main() {
|
|
var counts: map[string, int] = {}
|
|
for w in "a b a c b a".split(" ") {
|
|
counts[w] += 1
|
|
}
|
|
print(counts)
|
|
}
|
|
```
|
|
```text
|
|
{a: 3, b: 2, c: 1}
|
|
```
|
|
|
|
(Only the compound forms `+= -= *= /= %=` do this. Plain *reading* a missing key with `m[k]` still stops the program.)
|
|
|
|
### Looping
|
|
|
|
Entries come out **in the order they were added**, so output is always predictable.
|
|
|
|
```rex
|
|
func main() {
|
|
var prices = {"tea": 2.5, "cake": 4.0}
|
|
for name, price in prices {
|
|
print(name, "costs", price)
|
|
}
|
|
for name in prices { // just the keys
|
|
print(name)
|
|
}
|
|
}
|
|
```
|
|
```text
|
|
tea costs 2.5
|
|
cake costs 4.0
|
|
tea
|
|
cake
|
|
```
|
|
|
|
### Maps are values too
|
|
|
|
`var b = a` copies the whole map. A map inside a struct is copied with the struct.
|
|
|
|
```rex
|
|
func main() {
|
|
var a = {"x": 1}
|
|
var b = a
|
|
b["y"] = 2
|
|
print(a.len(), b.len())
|
|
}
|
|
```
|
|
```text
|
|
1 2
|
|
```
|
|
|
|
Looking things up is fast: it does not slow down as the map grows. (`remove` has to
|
|
re-arrange the entries to keep their order, so it is slower on huge maps.)
|
|
|
|
Next: [Structs and enums](06-structs-and-enums.md)
|