Haskell: how to map a tuple?

Solution 1:

Here's a rather short point-free solution:

import Control.Monad (join)
import Control.Arrow ((***))

mapTuple = join (***)

Solution 2:

Searching at Hoogle gives no exact matches for (a -> b) -> (a, a) -> (b, b), which is the type you require, but it is pretty easy to do yourself:

mapTuple :: (a -> b) -> (a, a) -> (b, b)
mapTuple f (a1, a2) = (f a1, f a2)

Note, you will have to define a new function for 3-tuples, 4-tuples etc - although such a need might be a sign, that you are not using tuples like they were intended: In general, tuples hold values of different types, so wanting to apply a single function to all values is not very common.

Solution 3:

You could use Bifunctor:

import Control.Monad  (join)
import Data.Bifunctor (bimap)

join bimap (2*) (1,2)

This works not only for pairs, but for a number of other types as well, e.g. for Either.

Bifunctor is in base as of version 4.8. Previously it was provided by the bifunctors package.