Converting an expression to a function

I want to convert mathematica “expressions” into usable functions, for instance, go from the text “Abs[omega]” to a function f(omega) = abs(omega). I’ve seen this topic, which is helpful as it gives me a Julia expression corresponding to what I want.

However, I don’t know how to go from an “Expr” to a usable function in Julia. For instance, when I do

using SymPy
const sympy_parsing_mathematica = SymPy.PyCall.pyimport("sympy.parsing.mathematica")
mathematica2julia(s::AbstractString, substitutions::Pair{<:AbstractString,<:AbstractString}...) =
           SymPy.walk_expression(sympy_parsing_mathematica."mathematica"(s, Dict(substitutions...)))

f = mathematica2julia("Abs[omega]")

I’d like to be able to use f as f(omega), ex. compute (f(-1)). I know this is related to metaprogramming, which I am not familiar with, but even looking at the documentation I couldn’t figure it out.

A way to compile a function from an expression:

  | | |_| | | | (_| |  |  Version 1.5.0 (2020-08-01)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

julia> ex = :(x + 42)
:(x + 42)

julia> fun = @eval (x) -> $ex
#1 (generic function with 1 method)

julia> fun(10)
52

I was not able to make your example work, so not sure if this helps.

1 Like

Yes, this works for me, thanks a lot!