lambda syntax added

This commit is contained in:
sergeych committed 2025-06-02 14:02:01 +04:00
1 parent 2344e19857
commit 19a2a1d909
10 files changed
+342 -59

No files matched your search

+34 -9
View File
@@ -2,24 +2,24 @@
## Closures/scopes isolation
Each block has own scope, in which it can safely uses closures and override
outer vars:
> blocks are no-yet-ready lambda declaration so this sample will soon be altered
Each block has own scope, in which it can safely use closures and override
outer vars. Lets use some lambdas to create isolated scopes:
var param = "global"
val prefix = "param in "
val scope1 = {
var param = prefix + "scope1"
param
}
val scope2 = {
var param = prefix + "scope2"
param
}
// note that block returns its last value
println(scope1)
println(scope2)
println(scope1())
println(scope2())
println(param)
>>> param in scope1
>>> param in scope2
@@ -38,7 +38,9 @@ One interesting way of using closure isolation is to keep state of the functions
counter = counter + 1
was
}
}
}()
// notice using of () above: it calls the lambda block that returns
// a function (callable!) that we will use:
println(getAndIncrement())
println(getAndIncrement())
println(getAndIncrement())
@@ -49,4 +51,27 @@ One interesting way of using closure isolation is to keep state of the functions
Inner `counter` is not accessible from outside, no way; still it is kept
between calls in the closure, as inner function `doit`, returned from the
block, keeps reference to it and keeps it alive.
block, keeps reference to it and keeps it alive.
The example above could be rewritten using inner lambda, too:
val getAndIncrement = {
// will be updated by doIt()
var counter = 0
// we return callable fn from the block:
{
val was = counter
counter = counter + 1
was
}
}()
// notice using of () above: it calls the lambda block that returns
// a function (callable!) that we will use:
println(getAndIncrement())
println(getAndIncrement())
println(getAndIncrement())
>>> 0
>>> 1
>>> 2
>>> void