Haskell Language Lens Lenses compose


If you have a f :: Lens' a b and a g :: Lens' b c then f . g is a Lens' a c gotten by following f first and then g. Notably:

  • Lenses compose as functions (really they just are functions)
  • If you think of the view functionality of Lens, it seems like data flows "left to right"—this might feel backwards to your normal intuition for function composition. On the other hand, it ought to feel natural if you think of .-notation like how it happens in OO languages.

More than just composing Lens with Lens, (.) can be used to compose nearly any "Lens-like" type together. It's not always easy to see what the result is since the type becomes tougher to follow, but you can use the lens chart to figure it out. The composition x . y has the type of the least-upper-bound of the types of both x and y in that chart.