Redefining functions inside loops

Defining a function f inside a loop, using it and then redefining it to behave some other way actually does not work as I thought it would/should.

For instance, this

for i in 1.0:2.0
	f(a) = 10.0*a
	println(f(i))

	f(a) = a^2
	println(f(i))
end

gives me

1.0
1.0
4.0
4.0

while I was hoping for

10.0
1.0
20.0
4.0

Only the last definition of f is used through the entire loop.
So I’m intrigued, any reason for this?

Ok so minutes after posting this I realized that this makes perfect sense considering Julia is a compiled language (JIT) and not an interpreted one.

Since f was last defined to behave as a^2, the first definition of f was overwritten during compilation, long before 10.0*a could show up anywhere on my screen.

I love how Julia can be so interactive that I ended up forgetting it is actually compiled.

3 Likes