Search code examples
haskellhaskell-lensstate-monad

How to define Lens into the State value itself?


While trying to understand State monad and use of Lens with it, I arrived at a surprisingly trivial definition of a lens for a simple counter:

self :: ASetter s s s s
self = ($)

incrementUsingLens :: State Int ()
incrementUsingLens = self %= (+1)

Since

type ASetter s t a b = (a -> Identity b) -> s -> Identity t

In my case is just

type ASetter s s s s = (s -> Identity s) -> s -> Identity s

Is this is indeed a correct definition for a lens into a state variable? I'm worried that I might be missing some laws or other assumptions.


Solution

  • lens calls this do-nothing optic simple. Note that simple is an Equality, and Equality is at the very bottom of the optics hierarchy, which means you can use it not only as a do-nothing setter, but also as a do-nothing lens, prism, etc.

    I'm worried that I might be missing some laws or other assumptions.

    The setter laws say that, for a foo setter, over foo should follow the functor laws:

    over foo id = id
    over foo (g . f) = over foo g . over foo f
    

    If you try this with simple/id, you will find the laws hold trivially. The same goes for the other optic laws.