# Converting an expression to a function

**URL:** <https://discourse.julialang.org/t/converting-an-expression-to-a-function/44736>\
**Category:** New to Julia\
**Tags:** mathematica\
**Created:** [August 11, 2020, 8:25am UTC](https://discourse.julialang.org/t/converting-an-expression-to-a-function/44736 "2020-08-11T08:25:37Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![benoitseron](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@benoitseron](https://discourse.julialang.org/u/benoitseron)\
**Post date:** [August 11, 2020, 8:25am UTC](https://discourse.julialang.org/t/converting-an-expression-to-a-function/44736/1 "2020-08-11T08:25:37Z")

</div>

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](https://discourse.julialang.org/t/best-practices-for-converting-a-mathematica-expression-to-julia/18335) 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

```julia
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.

---

<div class="post-metadata">

**Author:** ![tisztamo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tisztamo/32/16200_2.png) [@tisztamo](https://discourse.julialang.org/u/tisztamo)\
**Post date:** [August 11, 2020, 8:46am UTC](https://discourse.julialang.org/t/converting-an-expression-to-a-function/44736/2 "2020-08-11T08:46:59Z")

</div>

A way to compile a function from an expression:

```julia
  | | |_| | | | (_| | | 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.

---

<div class="post-metadata">

**Author:** ![benoitseron](https://avatars.discourse-cdn.com/v4/letter/b/85f322/32.png) [@benoitseron](https://discourse.julialang.org/u/benoitseron)\
**Post date:** [August 11, 2020, 9:24am UTC](https://discourse.julialang.org/t/converting-an-expression-to-a-function/44736/4 "2020-08-11T09:24:56Z")

</div>

Yes, this works for me, thanks a lot!
