Lens

Basic Lens(getter, setter)

{-# LANGUAGE Rank2Types #-}
 
-- Lens as a getter & updater
data Lens s a = Lens
  { get :: s -> a
  , update :: (a -> a) -> s -> s
  }
 
-- set :: Lens s a -> a -> s -> set
-- set l a s = update l (const a) s
 
compose :: Lens b c -> Lens a b -> Lens a c
compose bc ab = Lens
  { get = get bc . get ab
  , update = update ab . update bc
  }
 
fstL :: Lens (a, b) a
fstL = Lens
  { get = \(x, y) -> x
  , update = \f (x, y) -> (f x, y)
  }
 
sndL :: Lens (a, b) b
sndL = Lens
  { get = \(x, y) -> y
  , update = \f (x, y) -> (x, f y)
  }
 
main = do
  print $ update fstL (+1) (1, 2)
  print $ update (sndL `compose` fstL) (*2) ((3, 4), 5)

参考文献