Record Syntax, Lenses and Prisms: Part 3 - Prisms

September 7, 2014


So what are prisms?

Prisms are like lenses just for sum types … - the most memorable sentence, but I don’t think very helpful at first glance.

So let us start with defining a sum type.

Pirate is a sum type - with different records in each constructor.

A tangent on sums and products


Why is the above called a sum type, just let us calculate the number of options we have in a sum type:

If I have a variable x :: Sum it has exactly three values it can be

  • x = One
  • x = Two
  • x = Three

so the sum of the number of constructors is the solution of how many options x can be.


So how come product types to their names - you might already guess it.

For a variable y :: Product we find y can be |Sum|×|Sum| many possible values:

  • y = P One One
  • y = P One Two
  • y = P One Three
  • y = P Two One
  • y = P Two Two
  • y = P Two Three
  • y = P Three One
  • y = P Three Two
  • y = P Three Three

So can anybody find what exponential types are?

The answer is functions

So the functions from Two -> THREE have exactly |Two|^|THREE| many elements.

Back to Prisms

The problem with lenses is that cpt some getters don’t make sense. For datatypes that have a special elements, so called monoids like String with "" we get special getters, but for Town for example …

So an easy way to get special elements is combining it with Maybe. And that’s what prisms are - getters with Maybe-values instead of errors.

So how do we get them - again as with prisms we (have to) build them with template haskell magic using

This magic words create “Constructors” _Captain, _FirstMate and _Marauder and the lens library provides functions preview, review and ^?.

Now what are those functions doing - they select one branch in a sum type.

But there is also an infix shortcut for preview - (^?) so we could have written the above cpt^._Captain or use it with accessor-like functions as hometown,ship,shanty or attributes.

So what about review?

The review function can create new things from the results of preview, well not exactly but almost and with use of (<$>) from Control.Applicative we can make them work together

So Prisms do not fix everything - but provide a safety layer for simple accessing stuff and sometimes for generating stuff as well.

So thats all I know about Lenses and Prisms - for understanding the type signatures - I still do not feel confident to present about.