Confused by behaviour of nested functions

Good question. The problem only occurs when you have conditionally defined nested functions, like this:

function foo()
  # which definition of f() will occur? who knows?
  if rand() < 0.5
    f(x) = x + 1
  else
    f(x) = x + 2
  end
  f(1)
end

If the definition isn’t inside a conditional (like the if block above), then everything works:

function foo()
  # this if fine
  f(x) = x + 1
  f(1)
end

But I totally agree that the former behavior is confusing. I would support making the former an error (or, of course, making it actually work as expected). Such a change would technically be breaking, though, so it might not be possible until Julia 2.0. I’d have to leave that question to the core devs.

1 Like