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

Leon_Niceday
Fri, 09 May 2025 03:29:11 +0000
New to Julia

Hi,
What is the advantage to having such a difference between how variables use another variables vs how functions use them?

# Assigning to variable
julia> a=1;

julia> b=a
1

julia> a="asdf";

julia> b
1
# OK, as expected
#
# Assigning to function
julia> a=1;

julia> fun()=a
fun (generic function with 1 method)

julia> fun()
1

julia> a="asdf";

julia> fun()
"asdf"

It doesn’t seem good that calling the function again returns a different value and that you cannot predict what the function will return until you run the code, unlike in case of assigning to a variable.

EDIT: after reading the first replies: above I wrote “Assigning to a function”, which is misleading ; I meant defining the function to use another variable.

53 posts - 14 participants