Haskell/Solutions/Lenses and functional references

Traversals
1.

Setters
1.

2.

Lenses at last
1.

2.

Prisms
1a.

The challenge lies in decoding the type of :

It is easier to get a general idea of what is going on if we specialise it to prisms that do not change types.

Given a  that aims at a possible target of type   within an ,   gives us a   that aims at a   function within a   function. If we go back to the original type, which allows type-changing prisms, we note that the /  and  /  pairs are swapped. That happens because the type variables of the prism appear in the arguments of the functions the lens deals with. We might say that  is contravariant, in a similar sense to the one we used when discussing contarvariant functors earlier in the chapter.

There is something very odd in what we just said that requires further explanation. What can possibly mean saying that a function is within another function? To answer that, let's have a look at the type of :

extracts a value from an  value. To do so, it relies on two functions: a  one that handles values wrapped by   and a   one to handle. is then a  that can be seen as being made of two components,   and , each of them handling one of  's constructors. These function components are what  modifies. It is in that sense that  uses a prism as a "first-class pattern". Any  function is necessarily doing pattern matching, deconstructing an   to produce its   result. and  allow us to modify the way such a function handles each pattern.

1b.