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

from Setfield to Accessors

Open rveltz opened this issue 1 year ago • 5 comments

Hi, I want to switch from Setfield to Accessors. However I dont know the supertype of @optic

julia> using Setfield

julia> (@lens _) isa Lens
true

julia> using Accessors

julia> (@optic _) isa PropertyLens
false 

Can anyone give me a hint please?

rveltz avatar Jun 07 '24 15:06 rveltz

There is none, optics are duck-typed:


julia> @optic _
identity (generic function with 1 method)

julia> @optic(_) === identity
true

It is the identity function.

jw3126 avatar Jun 07 '24 15:06 jw3126

I see.

To emulate a supertype, what do you think of

const AllLensTypes = Union{PropertyLens, IndexLens, ComposedOptic, typeof(identity)}
@optic(_) isa AllLensTypes

rveltz avatar Jun 07 '24 16:06 rveltz

Depends on what the goal is. In the same way that I would usually prefer function map(f, itr) over function map(f::Function, itr) I usually prefer optics to be duck-typed. But it is a tradeoff and if it suits your use-case, you can go with a definition like that. But it will neither cover every optic, nor will every instance of your AllLensTypes be a valid optic.

jw3126 avatar Jun 07 '24 17:06 jw3126

Probably const AllLensTypes = Union{PropertyLens, IndexLens, Function} is a reasonable approximation. Out of curiosity, do you have an example where you really need to constrain the type like this?

aplavin avatar Jun 07 '24 17:06 aplavin

mostly to help the user. I am so used to Setfield, I have to adapt to your new framework.

rveltz avatar Jun 07 '24 18:06 rveltz