🎓 A1Learner
🔍
0 of 47 lessons completed

Haskell Lens Getter and Setter

A simple lens is a pair holding a getter and a setter for one part. The pair gives one name to both operations on that part.

The first part of the pair reads

firstLens holds getFirst and setFirst together. fst takes the getter out of the pair.

data Pair = Pair Int Int deriving Show
getFirst :: Pair -> Int
getFirst (Pair x _) = x
setFirst :: Int -> Pair -> Pair
setFirst v (Pair _ y) = Pair v y
firstLens :: (Pair -> Int, Int -> Pair -> Pair)
firstLens = (getFirst, setFirst)
main :: IO ()
main = print ((fst firstLens) (Pair 3 4))

The second part of the pair writes

snd takes the setter out of the pair. The setter replaces the first element and keeps the second.

data Pair = Pair Int Int deriving Show
getFirst :: Pair -> Int
getFirst (Pair x _) = x
setFirst :: Int -> Pair -> Pair
setFirst v (Pair _ y) = Pair v y
firstLens :: (Pair -> Int, Int -> Pair -> Pair)
firstLens = (getFirst, setFirst)
main :: IO ()
main = print ((snd firstLens) 9 (Pair 3 4))

Reading then writing updates a part

Over reads the first element, adds ten, and writes the result back. The second element stays 4.

data Pair = Pair Int Int deriving Show
getFirst :: Pair -> Int
getFirst (Pair x _) = x
setFirst :: Int -> Pair -> Pair
setFirst v (Pair _ y) = Pair v y
firstLens :: (Pair -> Int, Int -> Pair -> Pair)
firstLens = (getFirst, setFirst)
main :: IO ()
main = print ((snd firstLens) ((fst firstLens) (Pair 3 4) + 10) (Pair 3 4))

Example

data Pair = Pair Int Int deriving Show
getFirst :: Pair -> Int
getFirst (Pair x _) = x
setFirst :: Int -> Pair -> Pair
setFirst v (Pair _ y) = Pair v y
getSecond :: Pair -> Int
getSecond (Pair _ y) = y
setSecond :: Int -> Pair -> Pair
setSecond v (Pair x _) = Pair x v
firstLens :: (Pair -> Int, Int -> Pair -> Pair)
firstLens = (getFirst, setFirst)
secondLens :: (Pair -> Int, Int -> Pair -> Pair)
secondLens = (getSecond, setSecond)
main :: IO ()
main = print ((snd secondLens) 20 ((snd firstLens) 10 (Pair 3 4)))

Key points

  • Simple lens: a pair of a getter function and a setter function.
  • Getter: the first part of the pair, used to read the value.
  • Setter: the second part of the pair, used to replace the value.
  • Use fst to take the getter from the pair and snd to take the setter.
  • Over: a new value built by reading with the getter and writing with the setter.

In this example, the setter from firstLens replaces the first element with 10, then the setter from secondLens replaces the second element with 20, and the printed pair shows both replacements.

Note

the pair itself stores no value and only stores the two operations.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which expression reads the first element of Pair 3 4 through firstLens?