← Back to Demos & Examples

oro_closures.vk

Raw .vk
// Stateful ORO closures, tail recursion (recur), mut buffers, and /or error recovery
// Track A (ORO VM) : veko run examples/oro_closures.vk
// Track A (.vko)   : veko compile --vko examples/oro_closures.vk -o dist/oro_closures.vko ; veko run dist/oro_closures.vko
// Track B (Wasm 3) : veko run --wasm examples/oro_closures.vk
// Track C (Native) : veko compile --native examples/oro_closures.vk -o dist/oro_closures.exe ; ./dist/oro_closures.exe
use [bytes, ascii, str]

make-counter = fn [start] [
	fn [step] [
		start = start + step
		start
	]
]

next-id = make-counter 100
println (next-id 1)
println (next-id 5)

// Tail-recursive factorial using `recur`
fact = fn [n acc] [
	if n <= 1 [return acc]
	recur (n - 1) (acc * n)
]
println (fact 6 1)

// Zero-alloc in-place mut buffer mutation + /or error handling
mut buf = bytes/with-cap 4kb
bytes/push-all mut buf (bytes/from-str '  hello veko!  ')
ascii/trim-right! mut buf
ascii/upper! mut buf
println (str/from-bytes buf)

missing = os/read-file/or 'does-not-exist.txt' ['fallback-content']
println missing