Last active
October 9, 2017 16:29
-
-
Save ityonemo/c1aaae8ae3b12681ff894f0a3739c227 to your computer and use it in GitHub Desktop.
AST-fun with julia
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
function simplify(e::Expr) | |
if e.head == :call | |
if e.args[1] == :+ | |
simplify_add(e) | |
end | |
end | |
end | |
function simplify_add(e::Expr) | |
terms = Dict{Symbol, Int}() | |
for idx in 2:length(e.args) | |
if typeof(e.args[idx]) <: Integer | |
terms[:_] = haskey(terms, :_) ? e.args[idx] + 1 : 1 | |
elseif typeof(e.args[idx]) <: Symbol | |
terms[e.args[idx]] = haskey(terms, e.args[idx]) ? terms[e.args[idx]] += 1 : 1 | |
end | |
end | |
#next, collate the values. | |
splice!(e.args, 2:length(e.args), [expr_mult(terms[s], s) for s in keys(terms)]) | |
e | |
end | |
expr_mult(v, s::Symbol) = s == :_ ? v : :($v * $s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
simplify_add(:(x + 1 + 3 + x))
==> 4 + 2x