[Haskell-cafe] mapFst and mapSnd

Shachaf Ben-Kiki shachaf at gmail.com
Fri May 31 04:15:22 CEST 2013


On Thu, May 30, 2013 at 7:12 PM, Shachaf Ben-Kiki <shachaf at gmail.com> wrote:
> One generalization of them is to lenses. For example `lens` has
> "both", "_1", "_2", such that "mapPair = over both", "mapFst = over
> _1", etc., but you can also get "fst = view _1", "set _2 = \y' (x,_)
> -> (x,y')", and so on. (Since "both" refers to two elements, you end
> up with "view both = \(x,y) -> mappend x y".) The types you end up
> with are simple generalizations of mapFoo, with just an extra Functor
> or Applicative (think mapMFoo):
>
> both :: Applicative f => (a -> f b) -> (a,a) -> f (b,b)
> both f (x,y) = (,) <$> f x <*> g y
>
> _2 :: Functor f => (a -> f b) -> (e,a) -> f (e,b)
> _2 f (x,y) = (,) x <$> f y
>
> With an appropriate choice of f you can get many useful functions.
>

I spoke too quickly -- your mapPair is something different. Indeed
bimap (or (***), if you prefer base) is the place to find it -- lenses
don't really fit here. My "both" is for mapping one function over both
elements.

    Shachaf



More information about the Haskell-Cafe mailing list