On Tue, Apr 26, 2016 at 12:58 PM, Milan Bouchet-Valat <nalimi...@club.fr> wrote: > Le mardi 26 avril 2016 à 12:52 -0400, Yichao Yu a écrit : >> On Tue, Apr 26, 2016 at 12:09 PM, Ali Rezaee <arv.ka...@gmail.com> 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. >> Just to be clear, a macro can't help here. You need to eval in global >> scope if you want to evaluate arbitrary expressions. > Well, a macro could replace "x" with the name of the first argument, > create a function from that and call it.
Well, I assume the string is runtime value so there's nothing a macro can do. If it is compile time value, then you might as well write the code directly instead of storing it in strings... > > Though if possible creating anonymous functions is clearly a cleaner > solution. > > > Regards > >> > >> > >> > 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 >> > > >> > >