Function that's `not defined` is defined

The body of code is structured as

function my_fcn(...)
  ...
  if ...
    ...
    θ_sed(r) = ...
    return θ_sed, ...
  else
    ...
    t_sed(r) = ...
    @show t_sed(50.0)
    @show 2atan(t_sed(50.0))
    θ_sed(r) = 2atan(t_sed(r))
    @show θ_sed(50.0)
    return θ_sed, ...
  end
end

where the body of else results in the following error.

image

I don’t understand how θ_sed fails to be defined. I even evaluated its body before it, and it @shows that 2atan(t_sed(50.0)) evaluates without error. Additionally, the definition of θ_sed inside the if body evaluates just fine.

The weird thing is that when I remove the if-else structure and replace it with with the body of else like so

function my_fcn(...)
  ...
  t_sed(r) = ...
  @show t_sed(50.0)
  @show 2atan(t_sed(50.0))
  θ_sed(r) = 2atan(t_sed(r))
  @show θ_sed(50.0)
  return θ_sed, ...
end

it doesn’t evaluate an error, and θ_sed gets defined as a function without error.

What’s going on here? Why can’t I evaluate θ_sed inside the else body?

You can’t conditionally define a function inside a function: https://github.com/JuliaLang/julia/issues/15602. Solution: don’t do that

3 Likes

I suppose I’ll place the if-else inside the definition of my function, and do some closure.

You can conditionally define an anonymous function without issues. For example, instead of

if y
  f(x) = ...

you can do

if y
  f = x -> ...
5 Likes