Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve @functor property order when reconstructing #70

Merged
merged 1 commit into from
Jul 9, 2023

Conversation

ToucheSir
Copy link
Member

Fixes #68.

I originally hoped to have just the NamedTuple overload, but it turns out we're still documenting reconstructing from a plain tuple: https://github.com/FluxML/Functors.jl/blob/v0.4.4/src/Functors.jl#L49-L62.

PR Checklist

  • Tests are added
    - [ ] Documentation, if applicable

@skyleaworlder
Copy link
Contributor

skyleaworlder commented Jul 9, 2023

As for plain tuple, it can be done using escfs like this (although assign_expr.args[1] might be a bit tricky):

      reconstruct(y) = begin 
          pos_val = Dict([(pos => val) for (pos, val) in enumerate(y)])
          pos_name = Dict([(pos => assign_expr.args[1]) for (pos, assign_expr) in enumerate($(escfs))])
          reconstruct(NamedTuple([(name, pos_val[pos]) for (pos, name) in pos_name]))
      end
julia> using Functors

julia> struct C
              a
              b
              c
              end

julia> @functor C (c, a)

julia> c = C(1,2,3)
C(1, 2, 3)

julia> cc, re = Functors.functor(c);

julia> map(float, cc)
(c = 3.0, a = 1.0)

julia> re(map(float, cc))
C(1.0, 2, 3.0)

julia> re((3.0, 1.0))
C(1.0, 2, 3.0)

@ToucheSir ToucheSir merged commit 0314d20 into master Jul 9, 2023
@ToucheSir ToucheSir deleted the bc/check-keys branch July 9, 2023 15:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

functor reconstructs unexpectedly due to the lack of checking NameTuple's keys.
3 participants