Are these functions/closures examples:
a = 1.0
b = 5.0
return a * t + b
f2(t) = a * t + b
f3 = t -> a * t + b
solver(f1, f2, f3)
the same with respect to performance?
Is this correct:
- f1 is a function.
- f2 is a function (?)
- f3 is a closure.
In the solver function, if we evaluate each function, they will have the same performance?
All of these are closures.
And they are all functions too (so
f isa Function will give true), just different syntax to do the same thing.
okay, but a closure builds a
struct with captured variables as elements, while I do not know what a function does.
Each function is an instance of its own type (a subtype of
log isa typeof(log) is true and
typeof(log) <: Function is also true.
Function is an abstract type in Julia. Structs can be made subtypes of
Function and can be made callable using the syntax:
struct MyStruct <: Function end
(s::MyStruct)(args...) = println(args...)
s = MyStruct(); s(1) is equivalent to
I don’t know if this answers your question, but others might be able to comment better on lowering and compilation techniques used for closures and functions.
This is good enough!
As always, thanks a lot for your help!
From a programming language theory perspective the issue is how to resolve free variables in the body of a function.
return a * t + b
has 2 free variables, a and b. But it was defined in a context where those free variables were bound, and so a closure captures those bindings into a structure.
For a function defined at the “toplevel”, then you can resolve the free variables as global variables. So in some sense a function at toplevel is a closure whose bindings are the toplevel bindings.
A non-closure function is also a
struct with captured variables as fields. It’s just has zero fields.