Home > Back-end >  How to use an expression in function from other function in julia
How to use an expression in function from other function in julia

Time:01-10

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

CodePudding user response:

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.

CodePudding user response:

Use a macro instead of function:

macro f(expr)
    Meta.parse("x -> x " * expr)
end

Now you can just do:

julia> filter(@f("<3"), [1,2,3])
2-element Vector{Int64}:
 1
 2
  • Related