ekobir
ekobir

Reputation: 1

How to alter an expression in generic function?

E.g.

function sq(x)
    x ^ 2
end

function sq2(x)
    (x+1) ^ 2
end

function fun(x)
    sq(x)
end

I would like to replace sq call with sq2 call so redefine fun generic function. My attempt below changes the call but wasn't able to redefine the function. Any help will be appreciated.

change(:fun, (Int,))

function analyze_expr(exp::Expr)
   for i = 1:length(exp.args)
      arg = exp.args[i]
      if(typeof(arg) == Expr)
         analyze_expr(arg)
      elseif(arg==symbol("sq"))
         exp.args[i] = symbol("sq2")
      end
   end

end

function change(sym::Symbol, params)
    func = eval(sym)
    func_code = code_lowered(func, params)
    func_body = func_code[1].args[3]
    analyze_expr(func_body)
    println("Printing function body:",func_body)
end

Upvotes: 0

Views: 391

Answers (1)

John Myles White
John Myles White

Reputation: 2929

I suspect you'll find it easier to do this kind of work using macros: http://docs.julialang.org/en/latest/manual/metaprogramming/

Given an existing function definition, the relevant thing in Julia isn't so much the syntax that generated it as the compiled machine code that resulted. To my knowledge, modifying the syntax won't (without some deep hacking in Julia's internals) have any effect on the compiled machine code.

Upvotes: 1

Related Questions