>
> I'm trying to write an unpack macro, just to learn a bit about
> meta-programming (I get it's probably not the best idea,
> but sometimes you learn a lot doing stupid things)
>

 Absolutely agreed! But bear in mind that this may be a hard macro to write
in the general case. Nevertheless, I can give you some pointers.

Firstly, @unpack n p isn't going to work in the way you want, because the
value of n will not be known (in principle) until runtime. It is possible -
the way to do it is to construct and evaluate a let binding, but doing this
every time the code runs will be *extremely* slow. Interpreted languages
like R sometimes offer these kinds of features because they avoid the
compiler overhead. You could also call eval(n) within the macro but that's
very brittle.

On the other hand, as long as you aren't going to change the value of n at
run time, you can reference it from within the macro itself - something
like (not tested)

const n = [:a, :b, :c]
macro unpack(p)
  Expr(:block, [:($(n[i]) = $p[$i]) for i = 1:length(n)])
end

@unpack [1,2,3] # Now a = 1, b = 2, etc.

The problem with this, then, is generalising it; you don't want to define
this macro for every set of parameters, after all. But if you want to avoid
that, you'll need to write a macro that writes a macro - I'll leave that as
an exercise for the reader.

Reply via email to