Anonymous function in function closure

You’re seeing an effect of WIP: redesign closures, then generic functions by JeffBezanson · Pull Request #13412 · JuliaLang/julia · GitHub which redesigned closures to be structs with fields corresponding to the closed-over values.

When you write:

julia> let
         a = 1
         f() = a + 1
         @show f.a
         @show f()
       end
f.a = 1
f() = 2

the compiler transforms it into (roughly):

julia> let
         a = 1
         
         # The anonymous funcion is turned into a `struct`
         struct Anonymous1{T}
           a::T
         end
         # Make intances of that `struct` type callable
         (anon::Anonymous1)() = anon.a + 1
         # Make `f` an instance of that `struct` type
         f = Anonymous1(a)
         @show f.a
         @show f()
       end
f.a = 1
f() = 2

But the other thing I would say is: don’t use this to implement OOP. Multiple dispatch is a really nice way to organize code, and it’s worth learning the way Julia is intended to be used rather than trying to stick all of your functions inside your types.

4 Likes