mauro3 / Parameters.jl

Types with default field values, keyword constructors and (un-)pack macros
Other
420 stars 31 forks source link

Request: add example of customized/specialized unpack in docs #110

Closed briochemc closed 4 years ago

briochemc commented 4 years ago

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)
mauro3 commented 4 years ago

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.

briochemc commented 4 years ago

OK I'll do that!

briochemc commented 4 years ago

Done!

mauro3 commented 4 years ago

Tnx! x-ref https://github.com/mauro3/UnPack.jl/pull/2