Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally define a function inside another function in Julia

Tags:

julia

Slow to learning newer julia syntax and scoping.

In Julia v1.1.1

what is the explanation for why the MWE below throws error "ff not defined" ?

N = 5;
typp = "b";
mu = 2;

function bigfun()

  function f(u,mu)
    ee = mu*u;
    return ee
  end

  function g(uv,mu)
    ee = (mu^2)*uv
    return ee;
  end

  while 1 == 1

    u = ones(N);
    if typp == "a"
      ff(u) = f(u,mu);
    elseif typp == "b"
      ff(u) = g(u,mu);
    end
    fu = ff(u);
    break;

  end

end

bigfun();
like image 428
dj_a Avatar asked Jan 11 '21 01:01

dj_a


1 Answers

This is a known bug in Julia: https://github.com/JuliaLang/julia/issues/15602. You can't define an inner function conditionally. There a few ways around this issue:

  1. Define ff as an anonymous function:
        if typp == "a"
          ff = u -> f(u,mu)
        elseif typp == "b"
          ff = u -> g(u,mu)
        end
        fu = ff(u)
    
  2. Define ff once, and add the conditional inside of it:
        function ff(u, typp)
          if typp == "a"
            f(u,mu)
          elseif typp == "b"
            g(u,mu)
          end
        end
        fu = ff(u, typp)
    
  3. Don't define the function ff at all. You don't need to, in the example you provided, just assign fu conditionally
        if typp == "a"
          fu = f(u,mu)
        elseif typp == "b"
          fu = g(u,mu)
        end
    
like image 131
giordano Avatar answered Oct 01 '22 20:10

giordano