Mutated lenses

Posted on 2017-04-07 by Oleg Grenrus lens

It's not an April's Fool day anymore, but don't take this seriously anyway. Tongue in cheek literate Haskell post on lenses (if interested in more serious ones, see Compiling Lenses, and Affine Traversal ).

A quote by metafunctor

Haskell is so advanced that a inordinate amount of literature is devoted to what in any standard language would be simple getters setters and loops.
For loops are too much for me, but getters and setters we can do (in Haskell).


#Mutated Lens

readSTRef and writeSTRef types are just right so we can pass them into lens

Unfortunately the type of view is too restrictive, so we have to define a polymorphic version:

Seems to work:


Let's define an imperative record, with mutable fields:

and a "lens" into the first field:

Now we can read and write through intField and stref. First we create a record, then read its field; after that we mutate the field and read it again:

If we run the program, it works:

The problem with this approach, is that we cannot drill through STRef s (STRef s) ....

#Serious bit

Normal lens are in (->), but we can work in Kleisli (ST s) too. So if we change all normal arrows to Kleisli (ST s) (yet unwrapped), we can define STLens:

They compose:

and we can redefine stref':

The following definitions for stview and stover are very similar to lens counterparts.




And we can now drill through multiple STRef!


So, yet another example that Haskell is good imperative language. And we can have controlled effects in imperative language, you just need expressive enough language. :)

You can run this file with

fetch the source from

Site proudly generated by Hakyll