Are functions the same as closures in this case?

Are these functions/closures examples:

function main()

  a = 1.0
  b = 5.0

  function f1(t)
    return a * t + b

  f2(t) = a * t + b

  f3 = t -> a * t + b

  solver(f1, f2, f3)
  return nothing

the same with respect to performance?

Is this correct:

  1. f1 is a function.
  2. f2 is a function (?)
  3. f3 is a closure.

In the solver function, if we evaluate each function, they will have the same performance?


All of these are closures.

1 Like

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 Function), so 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 println(1).

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.

function f1(t)
   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.

1 Like

A non-closure function is also a struct with captured variables as fields. It’s just has zero fields.


Thanks @yuyichao and @dlakelan!