Search code examples
juliaevalcode-generation

generating expressions and then checking them in Julia


My goal is to be able to generate a list of expressions, p.g., check that a number is in some interval, and then evaluate it.

I was able to do it in the following way. First, a function genExpr that creates such an Expr:

function genExpr(a::Real, b::Real)::Expr
  quote
    x < $(a + b) && x > $(a - b)
  end
end

Create two expressions:

e1 = genExpr(0,3)
e2 = genExpr(8,2)

Now, my problem is how to pass these expressions to a function along with a number x. Then, this function, checks if such a number satisfies both conditions. I was able to achieve it with the following function:

function applyTest(y::Real, vars::Expr...)::Bool
  global x = y
  for var in vars
    if eval(var)
      return true
    end
  end
  return false
end

This works, but the appearance of global suggests the existence of a better way of obtaining the same goal. And that's my question: create a function with arguments a number and a list of Expr's. Such function returns true if any condition is satisfied and false otherwise.


Solution

  • This looks like a you are probably looking into using a macro:

    macro genExpr(a::Real, b::Real)
      quote
        x-> x < $(a + b) && x > $(a - b)
      end
    end
    
    function applyTest(y::Real, vars::Function...)::Bool
        any(var(y) for var in vars)
    end
    

    Testing:

    julia> e1 = @genExpr(0,3)
    #15 (generic function with 1 method)
    
    julia> e2 = @genExpr(8,2)
    #17 (generic function with 1 method)
    
    julia> applyTest(0,e1,e2)
    true
    

    However, with this simple code a function just generating a lambda would be as good:

    function genExpr2(a::Real, b::Real)
      return x-> x < (a + b) && x > (a - b)
    end