Reputation: 83
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
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
Upvotes: 1