Functions
Functions are first-class citizens in REK. They can be assigned to variables, passed as arguments, and returned from other functions.
Defining Functions
Use the fn keyword followed by the name and parameters.
fn greet(name) {
return "Hello, " + name
}
log(greet("World"))
Anonymous Functions
You can create functions without names, often used as callbacks.
let add = fn(a, b) {
return a + b
}
log(add(5, 3))
Closures
REK functions capture their surrounding environment. This allows for powerful patterns like function factories.
fn makeCounter() {
let count = 0
return fn() {
count = count + 1
return count
}
}
let counter = makeCounter()
log(counter()) // 1
log(counter()) // 2
Higher-Order Functions
Since functions are values, you can pass them into other functions.
fn runTwice(callback) {
callback()
callback()
}
runTwice(fn() {
log("Running...")
})
Recursion
Functions can call themselves.
fn fib(n) {
if n <= 1 { return n }
return fib(n - 1) + fib(n - 2)
}
log(fib(10))