Search code examples
functionjuliaexpressionmetaprogramming

How to use an expression in function from other function in julia


When I try those code below:

function f(x)
    Meta.parse("x -> x " * x) |> eval
end

function g(x)
    findall(Base.invokelatest(f,x),[1,2,3]) |> println
end

g("<3")

Julia throws "The applicable method may be too new" error.

If I tried these code below:

function f(x)
    Meta.parse("x -> x " * x) |> eval
end

findall(f("<3"),[1,2,3]) |> println

Julia could give me corrected result: [1, 2]

How can I modify the first codes to use an String to generate function in other function, Thx!

Test in Julia 1.6.7


Solution

  • Do

    function g(x)
        h = f(x)
        findall(x -> Base.invokelatest(h, x) ,[1,2,3]) |> println
    end
    
    g("<3")
    

    The difference in your code is that when you write:

    Base.invokelatest(f, x)
    

    you invoke f, but f is not redefined. What you want to do is invokelatest the function that is returned by f instead.