In Haskell, I can easily map a list:
map (\x -> 2*x) [1,2]
gives me [2,4]
. Is there any "mapTuple" function which would work like that?
mapTuple (\x -> 2*x) (1,2)
with the result being (2,4)
.
In Haskell, I can easily map a list:
map (\x -> 2*x) [1,2]
gives me [2,4]
. Is there any "mapTuple" function which would work like that?
mapTuple (\x -> 2*x) (1,2)
with the result being (2,4)
.
You can also use lens to map tuples:
Or you can map over tuples with upto 10 elements:
To add another solution to this colourful set... You can also map over arbitrary n-tuples using Scrap-Your-Boilerplate generic programming. For example:
Note that the explicit type annotations are important, as SYB selects the fields by type. If one makes one tuple element type
Float
, for example, it wouldn't be doubled anymore.Here's a rather short point-free solution:
The extra package provides the
both
function in the Data.Tuple.Extra module. From the docs:You can use arrows from module
Control.Arrow
to compose functions that work on tuples.Your mapTuple then becomes
If with your question you asked for a function that maps over tuples of arbitrary arity, then I'm afraid you can't because they would have different types (e.g. the tuple types
(a,b)
and(a,b,c)
are totally different and unrelated).Yes, you would do:
fst
grabs the first data entry in a tuple, andsnd
grabs the second; so, the line of code says "take a tuple, and return another tuple with the first and second items double the previous."