I’m doing a bunch of code generation and came across a strange behaviour involving type stability, closures and variable captures. I reduced the problem to the following example:
function f(a, b)
_f = (x, y) -> begin
c = x * y
end
return _f(a, b)
end
is fully type stable, i.e. Base.return_types(f, (Float64, Float64))
returns Float64
, as I would expect, and that’s good. However,
function f(a, b)
_f = (x, y) -> begin
c = x * y
end
c = _f(a, b)
return c
end
is type-unstable, i.e., Base.return_types(f, (Float64, Float64))
returns Any
. The problem seems to be the double usage of the variable name c
, causing julia to somehow capture the variable and boxing it. Renaming either of the two c
s to something else makes the function type stable again.
Is there any way to prevent julia from trying to capture something that it shouldn’t? This would probably be my ideal solution (because of world-age problems, I can’t simply define the closures as functions in an outer scope either). I’ve tried playing around with let
but didn’t get anything to work. This was the approach in some of the other topics I found that seemed related.
Since this problem comes up for me in code generation, I’d rather not have to do variable renaming, because that would increase the complexity of my code by a lot, just to workaround something that honestly feels like a bug in the language.