Functors.jl icon indicating copy to clipboard operation
Functors.jl copied to clipboard

`@functor` for parametric constructors

Open theogf opened this issue 2 years ago • 5 comments

Suppose I have a type

using Functors
struct Foo{T1,T2}
  x::T2
  Foo{T1}(x::T2) where {T1,T2} = new{T1,T2}(x)
end

Then using

@functor Foo

will not manage to capture the T1 type:

x = Foo{Real}(2.0)
y, re = Functors.functor(x)
re(y)
ERROR: MethodError: no method matching Foo(::Float64)
Stacktrace:
 [1] (::var"#5#6")(y::NamedTuple{(:x,), Tuple{Float64}})
   @ Main ~/.julia/packages/Functors/qBIlC/src/functor.jl:23
 [2] top-level scope
   @ REPL[14]:1

using

@functor Foo{T} where {T}

is not helping more

theogf avatar Apr 19 '22 08:04 theogf

I suppose the solution is to dispatch on the makefunctor function?

theogf avatar Apr 19 '22 08:04 theogf

You could, although it is also possible to simply make a constructor that can additionally take the parametric types or not using internal constructors if possible.

DhairyaLGandhi avatar Apr 19 '22 09:04 DhairyaLGandhi

Can't you use the same approach as in https://github.com/FluxML/Functors.jl/issues/6#issuecomment-744895426?

devmotion avatar Apr 19 '22 09:04 devmotion

Yeah, that's cleaner than dispatching makefunctor. Still it would be nice to accept the syntax @functor Foo{T} where {T}.

theogf avatar Apr 19 '22 09:04 theogf

If any macro wizard knows how to do this, would be happy to take a PR!

ToucheSir avatar Apr 19 '22 21:04 ToucheSir