isebarn
isebarn

Reputation: 3940

Julia: Evaluate expressions from a dictionary

I have a list of expressions, f.x

"a1 || a4"
"a3 && a5

and a dictionary with the truth values of these

a1 -> true
a2 -> false

I need to evaluate expressions from the list, with the true/false values from the dictionary

Any ideas how this can be achieved easily? Any help is greatly appreciated

Upvotes: 3

Views: 367

Answers (2)

David P. Sanders
David P. Sanders

Reputation: 5325

What is f.x? What do you mean by a list? In future, please give working code, not code snippets like this.

In Julia you almost certainly do not want to store Julia code like a1 || a4 in strings, but rather as Julia expressions (which is what parse of a string actually gives):

ex = [:(a1 || a4), :(a3 && a5)]

Secondly, you probably don't want to use variables with names like this, but rather an array:

a = bitrand(5)   # 5 random bits
a[1]   # gives true

Then you would use

ex = [:(a[1] || a[4]), :(a[3] && [a[5])]

and you can just do

map(eval, ex)

which evaluates each expression in the vector.

If you think that using a[1] instead of a1 is too much typing, you can walk the syntax tree and replace a_i with a[i]. Or, if you have the strings, just use the replace function on the string:

replace("hello a3 a34", "a3", "a[3]")

(so be careful!)

Upvotes: 2

Chisholm
Chisholm

Reputation: 1076

I feel like there might be a more elegant solution but this will certainly get the job done.

truths = Dict("a1" => true, "a2" => false)
expressions = ["a1 || a4", "a1 && a2"]

for (key, value) in truths
    info("evaluating: '$key = $value'")
    eval(parse("$key = $value"))
end

for exp in expressions
    info("$exp => $(eval(parse(exp)))")
end

Upvotes: 4

Related Questions