An implementation of optics in Elm.
A lens, prism or a traversal.
The pr
and ls
are used to track review
and get
capabilities, leave them being type variables. The consumers of lens will try to unify either of these with Y
type (= ()
).
The s
, t
, a
and b
are "input object type", "output object type", "input part type"
and "output part type", accordingly.
This means that you can get a
from s
, and given a function a -> b
make a t
out of s
.
Later in this text I will use term "final" for "out" types and "initial" for "in" types.
Optic N ls s t a b
The lens is "not a prism".
Optic pr N s t a b
The prism is "not a lens".
Optic N N s t a b
The traversal is neither "lens" or "prism".
Optic pr ls s t a b
The isomorphism is both "lens" and "prism".
()
Use this type as replacement for pr
/ls
variable when they are in the
signature of the function that calls any of requiring eliminators (get
/
review
/is
).
Lens ls s s a a
Lens
that cannot change type of the object.
Prism pr s s a a
Prism
that cannot change type of the object.
Traversal s s a a
Traversal
that cannot change type of the object.
Iso pr ls s s a a
Iso
that cannot change type of the object.
lens : (s -> a) -> (s -> b -> t) -> Lens ls s t a b
A lens constructor.
Parameters are: getter and setter.
If the lens can change type of an object, the setter must return the object of a new type.
prism : (b -> t) -> (s -> Either t a) -> Prism pr s t a b
A prism constructor.
Parameters are: reconstructor and a splitter.
Reconstructor takes a final value and constructs a final object.
The splitter turns initial object either to final object directly (if initial object is of wrong variant),
or spits out a
.
traversal : (s -> List a) -> ((a -> b) -> s -> t) -> Traversal s t a b
A traversal constructor.
Parameters are: toList and a mapper.
We need toList
, because there is no Foldable
typeclass in Elm.
The mapper is a "mapSomething" function over s
.
iso : (s -> a) -> (b -> t) -> Iso pr ls s t a b
An isomorphism constructor.
id : SimpleLens ls s s
An identity optic.
o : Optic pr ls s t a b -> Optic pr ls a b x y -> Optic pr ls s t x y
Optical composition.
Lens
usageget : Optic pr Y s t a b -> s -> a
Retrieve the only element using a lens.
Prism
usagereview : Optic Y ls s t a b -> b -> t
Use prism to reconstruct.
is : Optic Y ls s t a b -> s -> Basics.Bool
Check if s is related to a prism.
Note: You can change Y
to pr
here and it will still compile.
I restricted it to prisms, because semantics for traversals
is kinda be questionable.
Traversal
s)getSome : Optic pr ls s t a b -> s -> Maybe a
Retrieve up to one element using any optic.
getAll : Optic pr ls s t a b -> s -> List a
Retrieve all elements using any optic.
over : Optic pr ls s t a b -> (a -> b) -> s -> t
Update over any optic.
assign : Optic pr ls s t a b -> b -> s -> t
Assign into any optic.