Files use .rex, the command is rex, and the crate, runtime prefixes, docs, editor files and examples all use the new name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
102 lines
1.9 KiB
Rexx
102 lines
1.9 KiB
Rexx
// A tree: a node holds a list of child trees (a list can hold the enum it is inside).
|
|
enum Tree {
|
|
Leaf(value: int)
|
|
Node(children: []Tree)
|
|
|
|
func sum(): int {
|
|
return match self {
|
|
Leaf(v) => v
|
|
Node(kids) => sum_all(kids)
|
|
}
|
|
}
|
|
|
|
func depth(): int {
|
|
return match self {
|
|
Leaf(_) => 1
|
|
Node(kids) => 1 + deepest(kids)
|
|
}
|
|
}
|
|
}
|
|
|
|
func sum_all(ts: []Tree): int {
|
|
var total = 0
|
|
for t in ts {
|
|
total += t.sum()
|
|
}
|
|
return total
|
|
}
|
|
|
|
func deepest(ts: []Tree): int {
|
|
var best = 0
|
|
for t in ts {
|
|
var d = t.depth()
|
|
if d > best {
|
|
best = d
|
|
}
|
|
}
|
|
return best
|
|
}
|
|
|
|
// Error handling with a plain enum.
|
|
enum Result {
|
|
Ok(value: int)
|
|
Err(msg: string)
|
|
}
|
|
|
|
func divide(a, b: int): Result {
|
|
if b == 0 {
|
|
return Result.Err("divide by zero")
|
|
}
|
|
return Result.Ok(a / b)
|
|
}
|
|
|
|
func show(r: Result) {
|
|
match r {
|
|
Ok(v) => print("ok:", v)
|
|
Err(m) => print("error:", m)
|
|
}
|
|
}
|
|
|
|
// Data inside an enum is a value like everything else.
|
|
enum Msg {
|
|
Quit
|
|
Say(text: string)
|
|
Batch(items: []string)
|
|
}
|
|
|
|
struct Inbox {
|
|
last: Msg
|
|
count: int
|
|
}
|
|
|
|
func main() {
|
|
var tree = Tree.Node([Tree.Leaf(1), Tree.Node([Tree.Leaf(2), Tree.Leaf(3)]), Tree.Leaf(4)])
|
|
print("sum", tree.sum(), "depth", tree.depth())
|
|
|
|
show(divide(10, 2))
|
|
show(divide(1, 0))
|
|
|
|
var m = Msg.Batch(["a", "b"])
|
|
var copy = m
|
|
match copy {
|
|
Batch(items) => {
|
|
items.push("c")
|
|
print("copy has", items)
|
|
}
|
|
_ => print("not a batch")
|
|
}
|
|
print("original still", m)
|
|
|
|
var inbox = Inbox{Msg.Say("hi"), 1}
|
|
var other = inbox
|
|
other.last = Msg.Quit
|
|
other.count += 1
|
|
print(inbox, other)
|
|
|
|
match inbox.last {
|
|
Say(t) => print("said", t)
|
|
Quit => print("quit")
|
|
Batch(_) => print("batch")
|
|
}
|
|
}
|