Search code examples
haskellhaskell-lens

Combine Lens into a Lens of a tuple


Given

data Person = Person { _name :: String }
makeClassy ''Person

which creates a

name :: Lens' Person String

I can define the following lens which uses name inside a tuple.

sndPerson :: Lens' (a, Person) (a, String)
sndPerson = lens
    (\(a, p) -> (a, p ^. name)) 
    (\(_, p) (a, n) -> (a, p & name .~ n))

Is there a nicer/canonical way to define sndPerson above?


Solution

  • alongside turns a pair of lenses into a lens that works over a pair.

    Because in the example you don't focus into the first component, you could simply pass id as the first lens.

    sndPerson :: Lens' (a, Person) (a, String)
    sndPerson = alongside id name