lens doesn't a ready-made combinator for that, presumably beacuase you can get illegal setters (or lenses) if the focuses of the components overlap.
data Trio a = Trio a a a
deriving (Show)
oneTwo :: Setter' (Trio a) (a, a)
oneTwo = sets $ \f (Trio x y z) -> let (x', y') = f (x, y) in Trio x' y' z
twoThree :: Setter' (Trio a) (a, a)
twoThree = sets $ \f (Trio x y z) -> let (y', z') = f (y, z) in Trio x y' z'
cheating :: Setter' (Trio a) (a, a)
cheating = sets $ \f x -> x & oneTwo %~ f & twoThree %~ f
GHCi> Trio 1 1 1 & cheating %~ bimap (2*) (2*) & cheating %~ bimap (3+) (3+)
Trio 5 10 5
GHCi> Trio 1 1 1 & cheating %~ (bimap (2*) (2*) <&> bimap (3+) (3+))
Trio 5 13 5
In your case, the nicest alternative to building the setter/traversal by hand (as you and Cristoph Hegemann are doing) seems to be liftA2 (>=>) :: ASetter' s a -> ASetter' s a -> ASetter' s a
, as suggested elsewhere by bennofs (thanks Shersh for the link). If you happen to have a lens to a homogeneous pair (or some other Bitraversable
) lying around, you can get the traversal out of it with both
:
data Foo = Foo
{ _bar, _baz :: Int
} deriving (Show)
makeLenses ''Foo
barBaz :: Iso' Foo (Int, Int)
barBaz = iso ((,) <$> view bar <*> view baz) (Foo <$> fst <*> snd)
GHCi> Foo 1 2 & barBaz . both %~ (2*)
Foo {_bar = 2, _baz = 4}
Yet another possibility is exploiting Data.Data.Lens
to get a traversal of all fields of a certain type:
{-# LANGUAGE DeriveDataTypeable #-}
import Control.Lens
import Data.Data.Lens
import Data.Data
data Foo = Foo
{ _bar, _baz :: Int
} deriving (Show, Data, Typeable)
makeLenses ''Foo
barBaz :: Traversal' Foo Int
barBaz = template
GHCi> Foo 1 2 & barBaz %~ (2*)
Foo {_bar = 2, _baz = 4}