Thanh Nguyen
Thanh Nguyen

Reputation: 83

In Julia, how to assign values to variables and evaluate the function

In a text file from an user, there is a string that reads, for example, “2*X+3*Y”.

I have to: (1) interpret the string as a function of two variables “X” and “Y”; (2) write these two variables to the monitor and ask for the input of the values of the variables from the user; and (3) using these values of the variables, I have to compute the value of the function.

Following this https://groups.google.com/forum/#!topic/julia-users/NOSg-cpFklY, the task (1) can be done:

vars(vs,_)=vs

vars(vs,s::Symbol)=isdefined(s) ? vs : push!(vs,s)

function vars(vs,e::Expr)

    for arg in e.args

        vars(vs,arg)

    end

    vs

end
extractvars(s::String)=vars(Set{Symbol}(),parse(s))

setvar=extractvars(“2*X+3*Y”) # then I have: Set([:X,:Y])

How can the tasks (2) and (3) be done?

Upvotes: 0

Views: 835

Answers (1)

Reza Afzalan
Reza Afzalan

Reputation: 5746

vars(vs,_)=vs;

vars(vs,s::Symbol)=isdefined(s) ? vs : push!(vs,s);

function vars(vs,e::Expr)
  for arg in e.args
    vars(vs,arg)
  end
  vs
end 

function anonyfun(s::ASCIIString) # create an anonymous function from string
  e=parse(s);
  a=:(()->$e);
  vars(a.args[1].args,e);
  eval(a),length(a.args[1].args); # return function, length of args
end

foo,len=anonyfun("2*X+3*Y"); ; # => (anonymous function), 2

foo([parse(Float64,readline()) for i=1:len]...) # binding user inputs
  1. It simply works but what are the arguments type?
  2. To boost anonymous function performance: FastAnonymous

Upvotes: 1

Related Questions