Tutorial on closures?

I want to learn more about closures and their use with Julia. Does anyone recommend any paper/tutorial/book/blog post clearly explaining closures and what are their use cases for Julia programming? Most of the material that I have fond seems to be written for graduate students working in programming language theory…

This link Functional JS #4: Closures. What are Closures and what are they… | by Krzysztof Czernek | DailyJS | Medium might help understand them, although it’s examples are javascript. The concepts are the same. Similarly in Go: What is a Closure? - Calhoun.io. I assume you’ve seen the brief mention of closures in the julia manual.

I have a related answer on Stack Overflow that you could take a look at:

However, I should edit that answer. My first sentence is not quite correct:

You usually only define a function inside another function if you want to return a closure.

Sometimes it is handy to define an inner function (closure) that you will only use inside the particular function that you’re in (without actually returning the closure). Not to mention that whenever you create a function in a local scope, it is actually a closure. So, for example, if you use map(x) do ... end inside a function, the do syntax is creating a closure.

Also, you can create closures with a let block:

julia> let
           y = 1
           global f(x) = x + y
       end
f (generic function with 1 method)

julia> f(2)
3
3 Likes

I have some notes on that: https://m3g.github.io/JuliaNotes.jl/stable/closures/

6 Likes

Very helpful.

Are closures typically used for small functions like the examples? Would anyone, say, return a 500 line function as a closure?

Not neessarily. You can use to closure just to pass parameters to a more complicated function:

julia> v = rand(10);

julia> function f(x)
         if x < 0.5
           true
         else
           false
         end
       end
f (generic function with 2 methods)

julia> findall(x -> f(x), v)
6-element Vector{Int64}:
 2
 5
 6
 7
 8
 9

Or there is where the do syntax appears:

julia> findall(v) do x
         if x < 0.5
           true
         else
           false
         end
       end
2-element Vector{Int64}:
 5
 8

where that do x <body> means x -> <body> and is passed as the first argument of findall (which is omitted there.

2 Likes