Skip to content
justinmann edited this page Dec 25, 2017 · 2 revisions

Lambda functions are a convenient way to implement small pieces of functionality without the overhead of create a new function/class. This also implicitly capture the state of the calling function.

arr : [1, 2, 3]
total := 0
arr.each(^(i:'i32) { total += i; void })

// Or you can skip the function arg definition
arr.each(^{ total += _; void })

// Now for functions with multiple arguments
arr.foldl!i32(1, ^{ _1 + _2 })

// Lambda can live beyond the scope of the enclosing function
storeForLater(cb : 'heap (:i32)i32) { this }
a : heap ^(i : 'i32) { i + 10 }
storeForLater(a)

// Heap lambdas copy the enclosing state
total := 0 
arr.each(heap ^(i:'i32) { total += i; void })
// total will still be "0"

Clone this wiki locally