Tutorial by Examples

Getting ("a", 1) ^. _1 -- returns "a" ("a", 1) ^. _2 -- returns 1 Setting ("a", 1) & _1 .~ "b" -- returns ("b", 1) Modifying ("a", 1) & _2 %~ (+1) -- returns ("a", 2) both Traversal (1, 2) & bot...
Simple record {-# LANGUAGE TemplateHaskell #-} import Control.Lens data Point = Point { _x :: Float, _y :: Float } makeLenses ''Point Lenses x and y are created. let p = Point 5.0 6.0 p ^. x -- returns 5.0 set x 10 p -- returns Point { _x = 10.0, _y = 6.0 } p & x +~ ...
Lens operators have useful variants that operate in stateful contexts. They are obtained by replacing ~ with = in the operator name. (+~) :: Num a => ASetter s t a a -> a -> s -> t (+=) :: (MonadState s m, Num a) => ASetter' s a -> a -> m () Note: The stateful variants ar...
To demystify Template Haskell, suppose you have data Example a = Example { _foo :: Int, _bar :: a } then makeLenses 'Example produces (more or less) foo :: Lens' (Example a) Int bar :: Lens (Example a) (Example b) a b There's nothing particularly magical going on, though. You can write ...
A Lens' s a means that you can always find an a within any s. A Prism' s a means that you can sometimes find that s actually just is a but sometimes it's something else. To be more clear, we have _1 :: Lens' (a, b) a because any tuple always has a first element. We have _Just :: Prism' (Maybe a) a...
A Traversal' s a shows that s has 0-to-many as inside of it. toListOf :: Traversal' s a -> (s -> [a]) Any type t which is Traversable automatically has that traverse :: Traversal (t a) a. We can use a Traversal to set or map over all of these a values > set traverse 1 [1..10] [1,1,1,...
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 ...
In addition to the standard makeLenses function for generating Lenses, Control.Lens.TH also offers the makeClassy function. makeClassy has the same type and works in essentially the same way as makeLenses, with one key difference. In addition to generating the standard lenses and traversals, if the ...
(This example copied from this StackOverflow answer) Let's say you have a number of different data types that all ought to have a lens with the same name, in this case capacity. The makeFields slice will create a class that accomplish this without namespace conflicts. {-# LANGUAGE FunctionalDepen...

Page 1 of 1