logo

Metaprogramming in Julia 📂Julia

Metaprogramming in Julia

Code 1

Julia supports meta programming at the language level. The following is the result of reading and executing a string as code itself.

julia> text = "f(x) = 2x + 1; f(2)"
"f(x) = 2x + 1; f(2)"

julia> code = Meta.parse(text)
:($(Expr(:toplevel, :(f(x) = begin
          #= none:1 =#
          2x + 1
      end), :(f(2)))))

julia> eval(code)
5
  • Meta.Parse(): This function converts the input string into an expression and returns it.
  • eval(): It evaluates the expression. In the example code above, $f(2)$ is actually evaluated to get the function value $5$.

Environment

  • OS: Windows
  • julia: v1.5.0