Le mardi 26 avril 2016 à 08:38 -0700, Ali Rezaee a écrit :
> Hi everyone,
>
> I am trying to run the code below. When I try the code outside of a
> function and in REPL, it runs successfully. However when I run it
> using a function it throw an error.
> Why do I get the error? and how can I solve this problem?
This is because eval() evaluates the expression in the global scope,
where x does not exist. If you really need to parse expressions like
this, make evaluate() a macro which will create a Julia expression from
its arguments.
Regards
> Thanks in advance for your help.
>
> rules = ["(x[1] && x[2])", "(x[3] || x[4])"]; # a list of boolean
> expressions
> boolList = [false, true, false, true]; # a boolean vector for every x
> in rules
>
> function evaluate(rules, boolList)
> x = boolList
> result = Array{Bool}(length(rules))
> for (i, rule) in enumerate(rules)
> result[i] = eval(parse(rule))
> end
> return result
> end
>
> evaluate(rules, boolList)
> # ERROR: UndefVarError: x not defined
>
> # but This will work:
> x = boolList
> result = Array{Bool}(length(rules))
> for (i, rule) in enumerate(rules)
> result[i] = eval(parse(rule))
> end
>
> result
> # 2-element Array{Bool,1}: false true
>
>