On Wed, 7 Apr 2021 05:20:02 -0700 (PDT)
Fred Weigel <
fred_...@hotmail.com> wrote:
> Closures are very interesting. No, PASCAL doesn't have them. Makes sense
> in systems that have functions as first class things. Here is a very
> simple example.
>
> v <-5
> f(x) <- return x + v
>
> f(x) returns a function (notice the return -- and, I am making up the
> syntax) . g <- f(1)
g becomes the function return 1 + v
> Now, g(x) is a function:
I think not, as you have written it g() is a function that equates
to { return 1 + v } - by passing 1 as x you have created a function in which
x is fixed and v is supplied from the enclosing environment, but g takes no
parameters.
> g(1) gives 6 (1 + 5) -- because x was passed, and v was "closed over".
What is the 1 being passed to g() doing ? The 1 passed to f() in
order to generate g() set x in g() to 1 and v comes from the closure so
there is nowhere for a parameter to g() to go.
Otherwise what is the 1 you passed to f() doing ? You have it doing
nothing at all.
To quote from the Scala documentation:
-----------
A closure is a function, whose return value depends on the value of one or
more variables declared outside this function.
-----------
Closures do not require functions as first class objects in order
to exist, but they only really become useful when you can return the
function that references a variable to a scope that doesn't know the
variable exists.
In this example the closure is that logger() has access to prefix
from the enclosing scope of make_logger - it is called from inside and
outside that scope with the value of prefix changing between the calls -
again syntax is made up.
---------------------------------------------------
make_logger(passed_prefix) {
prefix = "Dummy"
logger(msg) {
print(prefix + ":" + msg)
}
logger("Inside make_logger") // Enclosed is enough for this usage
prefix = passed_prefix
return logger // But this needs functions as objects
}
logger = make_logger("My Silly Function")
logger("Outside make_logger") // So that prefix can have effect here
------------------------------------------
The first call to logger("Inside make_logger") will see prefix with the
value dummy, however by the time logger gets returned it will have the
value "My silly function".