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

Hello and welcome! You didn’t actually post any code. If you are redefining functions inside a loop, you have to make sure those are anonymous functions, as named functions are defined once only.

See this related issue Same code in if and else blocks, get UndefVarError only on else condition

5 Likes

Sorry for reviving an old thread, but I came across some difficulties regarding this topic and my google search lead me here.

Since OP didn’t post their code, we can’t be sure about what was their actual problem. However, as @baggepinnen pointed out, I think they might’ve been expecting something along the lines of what I reported here.

In my specific case, I had to redefine a function inside a nested loop. Before considering @baggepinnen use of anonymous functions, I thought about the the following solution. Basically it creates each function inside it’s own nested loop and then stores them in a vector of vectors, so that each function can then be accessed when needed.

n = 5
m = 2
funcs = Vector{Function}(undef, n)
funcs_arr = fill(funcs, m)

for i in 1:m
	funcs = Vector{Function}(undef,n)
	for j in 1:n
		f(x) = i^2+j
		funcs[j] = f
	end
	funcs_arr[i] = funcs
end

# Check Results
for i in 1:m
	for j in 1:n
		println(funcs_arr[i][j](1))
	end
end

#julia>
#2 
#3
#4
#5
#6
#5
#6
#7
#8
#9

I thought of leaving this for future reference and critique.
I also wonder which method would be preferred, this one or redefining anonymous functions, since I recall mentions of anonymous functions not being as fast as regular ones (but I’m not sure if that still holds as of Julia 1.3).

That was true back in Julia 0.4, but it hasn’t been true since then. Anonymous functions are the right tool for the job.

2 Likes