Add bit operators, defer, list methods, rand, assert and rex test
- 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>
This commit is contained in:
1 parent
910bde692a
commit
300d767124
28 files changed
+1373
-65
No files matched your search
@@ -30,6 +30,68 @@ func main() {
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user