Created
April 24, 2021 17:31
-
-
Save matthieubulte/2f709e8f077929983d3a67bbfc341d65 to your computer and use it in GitHub Desktop.
Symbolic expression from a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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