Thomas
Thomas

Reputation: 1205

Julia create function from string

In Julia v1.01 I would like to create a function from a string.

Background: In a numerical solver, a testcase is defined via a JSON file. It would be great if the user could specify the initial condition in string form.

This results in the following situation: Assume we have (from the JSON file)

fcn_as_string = "sin.(2*pi*x)" 

Is there a way to convert this into a function fcn such that I can call

fcn(1.0) # = sin.(2*pi*1.0)

Performance is not really an issue, as the initial condition is evaluated once and then the actual computation consumes most of the time.

Upvotes: 3

Views: 906

Answers (2)

Gauthier Soleilhac
Gauthier Soleilhac

Reputation: 386

Can't get my code displayed correctly in a comment so here's a quick fix for crstnbr's solution

function fcnFromString(s)
    f = eval(Meta.parse("x -> " * s))
    return x -> Base.invokelatest(f, x)
end

function main()
    s = "sin.(2*pi*x)"
    f = fcnFromString(s)
    f(1.)
end

julia> main()
-2.4492935982947064e-16

Upvotes: 6

Alex338207
Alex338207

Reputation: 1905

The functions Meta.parse and eval allow you to do this:

fcn_as_string = "sin.(2*pi*x)" 
fcn = eval(Meta.parse("x -> " * fcn_as_string))
@show fcn(1.0)

This return -2.4492935982947064e-16 (due to rounding errors).

Upvotes: 4

Related Questions