Converts the given string into code with metaprogramming

Apart from “please try to avoid doing this in the first place” this is hard to answer properly without knowing how it’s going to be used and how the example is supposed to generalize.

Here is another approach that may or may not be useful:

julia> function foo(s, x)
           f = eval(Meta.parse("x -> $s"))
           return Base.invokelatest(f, x)
       end
foo (generic function with 1 method)

julia> foo("2x+1", 3)
7

Cf. Passing a string into function as a expression - #14 by GunnarFarneback

4 Likes