Louis Pan
Louis Pan

Reputation: 115

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?

Upvotes: 4

Views: 735

Answers (1)

danidiaz
danidiaz

Reputation: 27766

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

Upvotes: 7

Related Questions