Closures in Julia

Julia supports anonymous functions, which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

# This function `int_seq` returns another function, which
# we define anonymously in the body of `int_seq`. The
# returned function closes over the variable `i` to
# form a closure.
function int_seq()
    i = 0
    return function()
        i += 1
        return i
    end
end

# We call `int_seq`, assigning the result (a function)
# to `next_int`. This function value captures its
# own `i` value, which will be updated each time
# we call `next_int`.
next_int = int_seq()

# See the effect of the closure by calling `next_int`
# a few times.
println(next_int())
println(next_int())
println(next_int())

# To confirm that the state is unique to that
# particular function, create and test a new one.
new_ints = int_seq()
println(new_ints())

To run the program, save it to a file (e.g., closures.jl) and use the Julia REPL or run it from the command line:

$ julia closures.jl
1
2
3
1

In Julia, closures work similarly to other languages. The int_seq function returns an anonymous function that increments and returns a counter. Each time we call int_seq, it creates a new closure with its own independent state.

The last feature of functions we’ll look at for now is recursion.