Skip to content

Instantly share code, notes, and snippets.

@phipsgabler
Created August 29, 2020 13:39
Show Gist options
  • Save phipsgabler/a1f6b3acac8a664bd4e72cbb2a5e4993 to your computer and use it in GitHub Desktop.
Save phipsgabler/a1f6b3acac8a664bd4e72cbb2a5e4993 to your computer and use it in GitHub Desktop.
julia> macro unpacker(expr)
           (expr.head != :(=) || length(expr.args) != 2) && error("Expression needs to be of form `name = value`")
           name, value = expr.args
           @gensym(props, x)
           return esc(quote
               $props = propertynames($value)
               macro $name($x)
                   return Expr(:(=), Expr(:tuple, $props...), $x)
               end
           end)
       end
@unpacker (macro with 1 method)

julia>  @unpacker unpack_thing = (a = 1,)
@unpack_thing (macro with 1 method)

julia> @unpack_thing (a = 2,)
(2,)

julia> a
2
@phipsgabler
Copy link
Author

Maybe the preferrable syntax would be @unpacker (a = 1,) => unpack_thing or something like that. And perhaps one should distinguish @field_unpacker and @property_unpacker. That's left as an exercise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment