Skip to content

Instantly share code, notes, and snippets.

@jonathanBieler
Created December 20, 2019 14:56
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 jonathanBieler/632cefb93ffdc07e3ee07feaad96c631 to your computer and use it in GitHub Desktop.
Save jonathanBieler/632cefb93ffdc07e3ee07feaad96c631 to your computer and use it in GitHub Desktop.
using MacroTools, MLStyle, Test
subst(a) = MLStyle.@match a begin
:(sin($x)) => :(cos($x + 1))
_ => a
end
MacroTools.prewalk(subst, quote
sin(x + sin(x))
end)
macro search_and_replace2(ex, s, r)
ex = Expr(:quote, ex)
s = Expr(:quote, s)
r = Expr(:quote, r)
esc(quote
subst(a) = MLStyle.@match a begin
$s => $r
_ => a
end
MacroTools.prewalk(subst, $ex)
end)
end
ex = @search_and_replace2 sin(x) sin(x) cos(x)
@test ex == :( cos(x) )
ex = @search_and_replace2 sin(y) sin($x) cos($x)
@test ex == :( cos(y) )
ex = @search_and_replace2 sin(sin(x)) sin($x) cos($x +1)
@test ex == :( cos(cos(x+1) +1) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment