ptr
Boxed mutable references - wrap any value in a {v} box, check whether an object is a valid box, read the contained value, replace it, atomically swap two boxes, apply an update function in place, compare two boxes by their contained values, and shallow-copy a box.
Load with: use ptr
What this module does
ilusm values are normally immutable and passed by copy. ptr
introduces a lightweight box - an object {v: value} -
that provides a stable identity you can share across closures and mutate in
place. Any code holding the same box object sees the same v
field, making shared mutable state explicit and opt-in.
ptr is also the foundation for uns (unsafe) and
mem (memory management), which build on boxes for lower-level
operations.
Quick example
use ptr
counter = ptr.new(0)
# Read
prn(ptr.get(counter)) # 0
# Write
ptr.set(counter, 1)
prn(ptr.get(counter)) # 1
# Update in place with a function
ptr.upd(counter, \(n) n + 10)
prn(ptr.get(counter)) # 11
# Swap two boxes
a = ptr.new("hello")
b = ptr.new("world")
ptr.swap(a, b)
prn(ptr.get(a)) # "world"
prn(ptr.get(b)) # "hello"
# Compare
x = ptr.new(42)
y = ptr.new(42)
prn(ptr.eq(x, y)) # tru
# Copy
z = ptr.cpy(x)
ptr.set(z, 99)
prn(ptr.get(x)) # 42 (independent copy)
Functions
Construction and inspection
ptrne(v) / ptr.new(v) / ptr.mk(v)Creates a new box containing v. Returns {v: v}.
ptris(p) / ptr.is(p)Returns tru if p is an object with a v field (i.e. a valid box).
Reading and writing
ptrge(p) / ptr.get(p)Returns the value inside box p. Throws if p is not a valid box.
ptrse(p, v) / ptr.set(p, v)Replaces the value inside box p with v. Mutates in place. Throws if p is not a valid box.
ptrup(p, fn) / ptr.upd(p, fn)Calls fn(current_value) and stores the result back in the box. Returns the new value.
Utilities
ptrsw(pa, pb) / ptr.swap(pa, pb)Atomically exchanges the values of two boxes. Returns nil.
ptreq(pa, pb) / ptr.eq(pa, pb)Returns tru if the contained values of both boxes are equal.
ptrco(p) / ptr.cpy(p)Creates a new independent box containing the same value as p. The two boxes are distinct objects thereafter.
Notes
- Requires
eru. - Used by
memandunsas their underlying mutable cell.