How to copy Mathematica expression into a Julia function

Very similar questions were asked before in the discourse (see e.g. this, this, and this). Answers point to MathLink where one can plug an expression like this

using MathLink
sqx = W`Sqrt[x]`

and then evaluate this function like so

weval(sqx; x=2.0)
# 1.4142135623730951

I would like to define a normal Julia function like

f(x) = sqrt(x)

using sqx above. Is there a way to do that?

My end goal is to be able to take the string output from Mathematica and edit some of the variables to define such a function f(x).

Why not simply

using MathLink
const sqx = W`Sqrt[x]`
f(x) = weval(sqx; x=x)

?

I assume you mean?

f(x) = weval(sqx; x)

When I plug a number to this f I get the following type

typeof(f(2))
# MathLink.WExpr

I would like to get just a Float64.

f(x) = weval(Float64, sqx; x)

?

1 Like

I am reviving this post with a follow-up question.

Is there a way to get an expression from mathematical, for example Sqrt[x y] to be typed in julia like

Sqrt[x y] 

would be

sqrt(x*y)

Thanks!

See: Best Practices for converting a Mathematica expression to Julia - #3 by stevengj

1 Like

For completeness, the answer I was looking for was given in this post and this is the solution (for more details read the thread in the other post).

using SymPy
const sympy_parsing_mathematica = SymPy.PyCall.pyimport("sympy.parsing.mathematica")

s = "(Sqrt[Pi])/(2*EllipticE[m])"
ex = sympy_parsing_mathematica.mathematica(s, Dict("EllipticE[x]"=>"elliptic_e(x)"))

# option 1
SymPy.walk_expression(ex, fns=Dict("Pow"=>:^)) 
#:((1 / 2) * pi ^ (1 / 2) * elliptic_e(m) ^ -1)

# option 2 (should work soon after some updates of SymPy)
SymPy.convert_expr(ex, use_julia_code=true) 
# :(sqrt(pi) ./ (2 * elliptic_e(m)))