Next we can take advantage of a bunch of operators introduced in Lens. Similar to monadic function composition we saw in Kleisli, LensT implements compose (symbolic alias <=<), and andThen (symbolic alias >=>). I personally think >=> looks cool, so let’s use that to define turtleX:

We are now describing change of internal values upfront and passing in the actual value at the end. Does this remind you of something?

Lens as a State monad

That sounds like a state transition to me. In fact Lens and State I think are good match since they are sort of emulating imperative programming on top of immutable data structure. Here’s another way of writing incX:

Now we have implemented forward function without using a single copy(position = ...). It’s nice but we still needed some prep work to get here, so there is some tradeoff. Lens defines a lot more methods, but the above should be a good starter. Let’s see them all again:

Finally, there’s a compiler plugin by Gerolf Seitz that generates lenses: gseitz/Lensed. The project seems to be at experimental stage, but it does show the potential of macro or compiler generating lenses instead of hand-coding them.