Request: add example of customized/specialized unpack in docs
briochemc opened this issue · 4 comments
I think it would help to have an example of how to specialize the unpack
function.
So far I have been redefining the getproperty
function (the effect of which is mentioned in the docs), but reading through the "customization" part of the docs seems to suggest one should instead add methods to unpack
. However, there is no example of that, and I failed at trying it. As a MWE, trying to multiply by 2
while unpacking via
@inline unpack(p::T, ::Val{f}) where {f} = 2 * getproperty(x, f)
where T
is my custom type, did not work for me. (FWIW in my case I was trying to do some scaling, specifically converting to SI units to be precise.)
So I would love to be taught how to do this properly, but I think an example in the docs would be great IMHO! 🙂
EDIT: OK I'm an idiot, I forgot to "import" unpack
... This worked for me:
@inline Parameters.unpack(x::T, ::Val{f}) where {f} = 2 * getproperty(x, f)
Maybe the MWE example below could be added anyway?
using Parameters
@with_kw struct Para{T}
a::T = 1.0
b::T = 2.0
end
p = Para()
@unpack a, b = p ; a, b # gives (1.0, 2.0)
@inline Parameters.unpack(x::Para, ::Val{f}) where {f} = 2 * getproperty(x, f)
@unpack a, b = p ; a, b # now gives (2.0, 4.0)
Sounds good, PR welcome. But note that for the example, no @with_kw
is needed as @unpack
works with any type. Also, I'm planning to split off pack/unpack into https://github.com/mauro3/UnPack.jl, so best to make the PR against that repo.
OK I'll do that!
Done!
Tnx! x-ref mauro3/UnPack.jl#2