Writing "Imperative Code" in Haskell: Lenses and the State Monad

Lenses: Basic Idea

  • A lens provides access into the middle of a data structure
  • A lens is a value of type Lens' s a
  • Lenses can be composed to "look deeper":
(.) :: Lens' r s -> Lens' s a -> Lens' r a

-- For example, if:
address        :: Lens' Person Address
city           :: Lens' Address City

-- Then:
address . city :: Lens' Person City

r

s

a

Lenses: Basic Functions

-- Get the focused element
view :: Lens' s a -> s -> a

-- Set the focused element
set  :: Lens' s a -> a -> s -> s

-- Modify the focused element
over :: Lens' s a -> (a -> a) -> s -> s

a

s

-- "Get"
use  :: MonadState s m => Lens' s a -> m a

-- "Set"
(.=) :: MonadState s m => Lens' s a -> a -> m ()

-- "Modify"
(%=) :: MonadState s m => Lens' s a -> (a -> a) -> m ()

In a State Monad:

deck

By Moritz Drexl

deck

  • 628