Skip to content

Instantly share code, notes, and snippets.

@matthieubulte
Created April 24, 2021 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthieubulte/2f709e8f077929983d3a67bbfc341d65 to your computer and use it in GitHub Desktop.
Save matthieubulte/2f709e8f077929983d3a67bbfc341d65 to your computer and use it in GitHub Desktop.
Symbolic expression from a string
using MacroTools
using Symbolics
function parse(strexpr)
expr = Meta.parse(strexpr)
freevars = Set()
expr = MacroTools.postwalk(x -> begin
if isa(x, Symbol) && !isdefined(Base, x)
push!(freevars, Variable(x))
Expr(:call, Variable, QuoteNode(x))
else
x
end
end, expr)
eval(expr), collect(freevars)
end
s, _ = parse("(x1 + x2)^2")
#> ((x1 + x2)^2, Any[x2, x1])
expand(s)
#> x1^2 + x2^2 + 2x1*x2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment