Record Syntax, Lenses and Prisms: Part 1 - Record Syntax

August 10, 2014

Intro

Pirates and Records

As a programmer you are often tasked with the problem of modelling reality and thus your customers have assigned you to make a complex data structure, something like a pirate captain and a gruesome crew of marauders.

In an object oriented approach one would start with designing a “plain old object” and inheriting a whole bunch of attributes. The haskell equivalent of objects are Algebraic Data Types or ADTs for short.

This definition above is quite similar to objects, but it actually defines a type which consists of three possible “constructors”, the last statement deriving (Show) is haskell’s way of saying we have a toString-method called show.

But your customers want to customize those Pirates (hence the name). So you decide to come up with a more accurate model of pirates.

The customers like the prototype - but as they are very unfamiliar with functional programming they ask you to prepare a little demo.

Still the customers is impressed with the prototype but still not content, so you start with designing a very detailed model starting with humans.

Then you come up with the nitty gritty details like Hat, Torso and so on.

The customer asks for a demo so you make a new crew based on the old examples.

Not really good and readable code so you try it a bit more verbose.

The last piece - a.k.a. the crew was not too easy in the first example so you don’t expect this to be a piece of cake, well it isn’t.

After the initial constructor the tricky part just begins - it takes four tries and a lot of hard thinking to get the following lambda expression right.

There are signs of bad code in this, a lot of signs - mrd is written three times, it is complicated not only to a programmer new to the haskell world.

But then there comes Edward Kmett’s lens library to the rescue.