Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created February 16, 2020 20:50
Show Gist options
  • Save tk3369/7487ddf3121d9412a7a08a880c661c13 to your computer and use it in GitHub Desktop.
Save tk3369/7487ddf3121d9412a7a08a880c661c13 to your computer and use it in GitHub Desktop.
How to use `@capture` with variable expression

How to use @capture with variable expression

The @capture macro from MacroTools expects one to pass the pattern directly when the macro is called. From Slack, someone asked if the pattern can be stored in a variable and then passed to the macro. I could make it work with the following "hack":

julia> code
:(foo(bar + xyz))

julia> pattern
:(phi1_(x_ + y_))

julia> x = :(@capture(code,pattern))
:(#= REPL[177]:1 =# @capture code pattern)

julia> x.args[3] = Expr(:quote, code)
:($(Expr(:quote, :(foo(bar + xyz)))))

julia> x.args[4] = pattern
:(phi1_(x_ + y_))

julia> eval(x)
true

julia> phi1, x, y
(:foo, :bar, :xyz)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment