Stream: helpdesk (published)

Topic: Interpolating operator in quoted expression


view this post on Zulip mbaz (May 03 2022 at 18:15):

This works:

julia> :( x + y )
:(x + y)

I'd like to interpolate an operator instead of having a hard-coded +. I can do this:

julia> op = :+
:+
julia> :( $op(x, y) )
:(x + y)

Is there a way to keep the x op y syntax? This fails:

:( x $op y )
ERROR: syntax: missing comma or ) in argument list

view this post on Zulip Gunnar Farnebäck (May 03 2022 at 18:47):

I doubt it. If it's not syntactically okay it's hard to get further. Of course you can do string interpolation and Meta.parse but you probably don't want that.

view this post on Zulip mbaz (May 03 2022 at 18:50):

Thanks! Yes, I thought of Meta.parse, but basically I was just wondering if I was missing something. The manual doesn't provide clarity about this.

view this post on Zulip mbaz (May 03 2022 at 18:53):

I'm not sure why it fails, though. My mental model (which is likely wrong) is that :( x $op y ) is first converted to :( x + y ); that is, interpolation happens before further parsing of the quote. Probably parsing occurs before interpolation.

view this post on Zulip Gunnar Farnebäck (May 03 2022 at 20:33):

It would be kinda hard to interpolate before parsing. E.g. making sense of

julia> op = [:+, :-]
2-element Vector{Symbol}:
 :+
 :-

julia> :($(op[2])(x, y))
:(x - y)

Last updated: Oct 02 2023 at 04:34 UTC