Reading the rules from a file, how can I convert the strings to such anonymous functions?
On Tuesday, April 26, 2016 at 6:48:21 PM UTC+2, Josh Langsfeld wrote: > > Maybe a better design would be to store the rules as anonymous functions > rather than code strings? Something like: > > ``` > rules = [(x -> x[1] && x[2]), (x -> x[3] || x[4])] #parentheses not > required > result = [rule(boolList) for rule in rules] > ``` > > On Tuesday, April 26, 2016 at 12:09:33 PM UTC-4, Ali Rezaee wrote: >> >> >> Thanks for your replies. >> My objective is exactly what the code shows. I have a list of Boolean >> expressions similar to the examples in the code, and I need to evaluate >> them one by one based on x values. >> So writing a macro would be the only solution. >> >> Best regards >> On Tuesday, April 26, 2016 at 5:38:21 PM UTC+2, Ali Rezaee wrote: >> >>> 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? >>> >>> 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 >>> >>> >>>