Why the free variables in function body don't get bound at function definition time?

This follows directly from Julia’s use of lexical scope.: the a in the functions you defined refers to the global variable a, not the value of the variable at definition.

I think it can help to realize that

fun() = a

isn’t assigning the value of a to a function, but rather is syntactic sugar for

function fun()
   return a
end

If you really want the behavior you described, then you need to close over / capture the value at definition time, i.e. you need a closure. You can do this with a let block:

julia> a = 1
1

julia> fun = let a2 = a
       function()
       return a2
       end
       end
#3 (generic function with 1 method)

julia> fun()
1

julia> a = 2
2

julia> fun()
1

julia> a2
ERROR: UndefVarError: `a2` not defined in `Main`
Suggestion: check for spelling errors or missing imports.
3 Likes