Search code examples
haskellhaskell-lenslenses

What's the difference between view and use in lens?


What's the difference between

view :: MonadReader s m => Getting a s a -> m a

and

use :: MonadState s m => Getting a s a -> m a

in Control.Lens.Getter?


Solution

  • Taking a look at the type signatures, view takes a MonadReader (such as ReaderT) and use takes a MonadState (such as StateT). Now, view and use both have the same objective: extract a reasonable value from the thing we're looking at.

    MonadReader represents read-only state. We can access the value within using ask. MonadState represents read-write state, which can be retrieved with get. So both view and use query the internal state of the monad given, but view calls ask whereas use calls get. Generally speaking, only one will be applicable to your situation.

    A look at the source code for the two functions is not particularly enlightening unless you already understand how lenses are implemented (and if you do, then you probably understand the difference between view and use), so this is a good example of a situation where the type signatures can be much more enlightening than the code itself.