Lambdas

Lambdas

Called as Units (type signature Unit), they are anonymous functions that can be stored in a variable, passed to a function and can be called with args.

// an anoymous lambda stored in a variable that can be called on demand!
let double(x: Int) = x * 2
 
println(double(5))  ; 10

An example demonstrating a real world scenario:

fn pow(n: Int, power: Int, callback: Unit) {
  n = copy(n) - 1   ; copy to not change original value
 
  for (var i = 0; i < n; i++) {
    var powed = copy(i)
    for (var j = 1; j < power; j++) {
      powed *= i
    }
    callback(i, powed)
  }
}
let power = 2
let callback(of: Int, powed: Int) {
  println(format("%d^%d is %d", of, power, powed))
}
pow(5, power, callback)

Here, a function pow() takes in a callback that reports back the powered values through a Unit (lambda).