Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: how to map a tuple?

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).

like image 525
quant_dev Avatar asked Mar 15 '12 15:03

quant_dev


People also ask

Can you map a tuple?

Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc.

How do you define a tuple in Haskell?

A tuple is a fixed-length coupling of values, written in parentheses with the values separated by commas. One way to use this is to pass all parameters into a function as one value, rather than the curried functions we've seen so far.

How do you make a tuple in Haskell?

Use parentheses and commas to create tuples. Use one comma to create a pair. Use more commas to create tuples with more components. Note that it is also possible to declare tuples using in their unsugared form.

How do I use a map in Haskell?

map is a function that takes two parameters: a function and a list of elements. The type signature of map is (a -> b) -> [a] -> [b] . The (a -> b) part is the function you pass to map , we will call it f . f takes one value and returns another that may be of a different type.


2 Answers

Here's a rather short point-free solution:

import Control.Monad (join) import Control.Arrow ((***))  mapTuple = join (***) 
like image 58
Rotsor Avatar answered Sep 25 '22 23:09

Rotsor


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.

like image 29
Boris Avatar answered Sep 22 '22 23:09

Boris