Files
rexlang/examples/basics/closures.rex
T
Your NameandClaude Opus 5.5 7cf9727bcd Rename the language from Dino to Rex
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>
2026-11-08 13:51:23 +01:00

75 lines
1.7 KiB
Rexx

struct Button {
label: string
on_click: func(string)
clicks: int
func click() {
clicks += 1
on_click(label)
}
}
func apply(f: func(int): int, x: int): int {
return f(x)
}
func twice(f: func(int): int): func(int): int {
return func(x: int): int { return f(f(x)) }
}
func make_counter(): func(): int {
var n = 0
return func(): int {
n += 1
return n
}
}
func double(x: int): int { return x * 2 }
func map[T, U](xs: []T, f: func(T): U): []U {
var out: []U
for x in xs { out.push(f(x)) }
return out
}
func filter[T](xs: []T, keep: func(T): bool): []T {
var out: []T
for x in xs {
if keep(x) { out.push(x) }
}
return out
}
func main() {
var offset = 10
var add = func(x: int): int { return x + offset }
offset = 99 // the closure kept its own copy
print(add(1), apply(add, 5), apply(double, 4))
print(apply(x => x * x, 7), twice(double)(3), twice(x => x + 1)(0))
var next = make_counter()
var other = make_counter()
print(next(), next(), next(), other())
var snapshot = next // copies the closure, with its state
print(next(), snapshot())
var nums = [1, 2, 3, 4, 5, 6]
print(map(nums, x => x * 10))
print(map(nums, x => "n{x}"))
print(filter(nums, n => n % 2 == 0))
var total = 0
for n in nums { total += apply(double, n) }
print(total)
var log = ""
var b = Button{"OK", func(name: string) { print("clicked", name) }, 0}
b.click()
b.click()
print(b.clicks)
var handlers: []func(int): int
handlers.push(double)
handlers.push(x => x - 1)
for h in handlers { print(h(10)) }
}