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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -