Typeclass Optics

Posted on 2018-03-08 by Oleg Grenrus lens

This is a short gist for Iceland_Jack. Thanks for nerd-snipping me on Twitter

This is literate Haskell file. Note, no extensions, plain (GHC-ish) Haskell2010.

For simplicity of presentation I will consider only simple optics, not optic families. Optics form sub-categories (I only started reading a book to understand what kind!?).

#Type classes

We define classes which let's construct various optics. Let's define Iso, Lens, Prism and Affine, they will illustrate enough of hierarchy:


Next we can define basic operations, for example over. We need concrete ASetter for that:


And we can run few examples:


Another basic operation is view. That's defined only for AGetters:


Note that we don't have Prism or Affine instance for Getters (i.e. Iso, Lens, but not Prism!). (We could have different folding view, which would have - that variant is in lens).

And the example:

#Error messages

We could used (->) directly as AGetter, but it helps with error messages:

After few steps we have profit!.

I want to conclude with a reference to The evolution of a Haskell Programmer, keep that in mind when you enable {-# LANGUAGE KitchenSink #-} ;)

This work is licensed under a “CC BY SA 4.0” license.

Site proudly generated by Hakyll