Julia macro splatting -
why work:
function test_func(a, b) + b end test_func((1, 2)...)
but not?
macro test_func(a, b) + b end @test_func((1, 2)...)
is bug in julia?
macros operate on surface syntax, @test_func
isn't seeing result of splat. instead, sees splat operation itself! always, great way inspect quote , see syntax macro operating on:
julia> :(@test_func((1,2)...)) :(@test_func (1,2)...) julia> meta.show_sexpr(ans) (:macrocall, symbol("@test_func"), (:..., (:tuple, 1, 2)))
so macro receiving 1 argument (not two), , it's expr(:..., expr(:tuple, 1, 2))
. notice tuple (1,2) is getting passed macro, it's hidden away inside splat operation. dig expr
, kind-of-sort-of implement splatting yourself:
julia> macro test_func(as...) if length(as) == 1 && isa(as[1], expr) && as[1].head == :... && isa(as[1].args[1], expr) && as[1].args[1].head == :tuple a, b = as[1].args[1].args elseif length(as) == 2 a, b = else error("unsupported syntax $as") end return esc(:($a + $b)) end julia> @test_func((1,2)...) 3
but kind-of-sort-of supports splatting. happens if try operate on variable instead:
julia> @test_func(xs...) error: unsupported syntax (:(xs...),)
there's no way macro know should adding together!
Comments
Post a Comment