A question about redefining a function in Julia

Hello. I just tested the following small code on Julia, and found that the value g() is changed after redefining the function f, but c is unchanged. I was wondering the reason behind this difference, and how to keep g() unchanged as well. Thanks.

f(x)=x+1
c=f(1)  #c=2
g()=f(1)  #g=2
f(x)=x+2
c  #c=2 unchanged
g()  #g=3 changed

g() calls the function f with 1 as argument.
If you change f to output argument + 2 instead of argument + 1, g() will use your changed function f.

Yes, I understand. But why doesn’t the value of c change as well?

I think it’s just because c refers to the value 2, which was computed by evaluating the expression (as it was defined at that time) f(1), while g is looking up whatever the current definition of f is when you call it, and then executing.

1 Like

c does not change because it took the value of f(1) before you changed the meaning of function f. g does change, because it calls function f. This allows you to have all sorts of functions and not having to worry to recompile all functions that use your changed f down the line, just recompile f.

I think so. But why c took the value of f at the time it was defined while g needed to look up the definition of f? c and g() were defined in the same way. Any mechanism behind it?

Functions run code. Assignments simply give names to values.

While f() = x and f = x look similar, they are wildly different things. The former defines a function that can be run later, whereas the latter gives another name to whatever value x is at that point.

4 Likes

Yes, but c and g() were defined in the same way, why do they behave differently when calling their values? Any mechanism about it?

explained by @mbauman just before you asked :slightly_smiling_face:

If you want your function be be more flexible, instead of redifining it every time, you could define it as follows:

f(x,y) = x + y
g(x) = f(3,x+2)   
# example, note the x is local to the function, 
# so the y in f becomes the value of x+2

julia>  c = f(1,1)   # c=2
julia>  c = f(1,2)   # c=3
julia>  c = g(2)    # c=7 

although I would not bother if the function is not more than one + etc. operator.

Thanks. This clarifies my confusion. By the way, is there any documentation related to the delayed run of functions?

Yes, the Manual page titled Functions. It’s also how functions work in programming generally, by whatever name in specific languages.

1 Like