Skip to content

Instantly share code, notes, and snippets.

@ityonemo
Last active October 9, 2017 16:29
Show Gist options
  • Save ityonemo/c1aaae8ae3b12681ff894f0a3739c227 to your computer and use it in GitHub Desktop.
Save ityonemo/c1aaae8ae3b12681ff894f0a3739c227 to your computer and use it in GitHub Desktop.
AST-fun with julia
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)
@ityonemo
Copy link
Author

ityonemo commented Oct 8, 2017

simplify_add(:(x + 1 + 3 + x))
==> 4 + 2x

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment