Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Applying 2 lambda expressions to list of tuples

I'm struggling to understand lambda expressions in Haskell.

Here is the problem:

I have a list of tuples [(a,b),(c,d),(e,f)...] (it can be of any length)

I want to apply two functions f1 and f2 to each tuple in the list, but in such a way that f1 is applied to the first element and f2 is applied to second element of each tuple.

So for example if I had [(a,b),(c,d)] I would like to apply f1 and f2 to end up with something like this: [((f1(a),f2(b)),(f1(c),f2(d))].

I think I can use map and lambda expression but I end up with type errors.

Is it possible to do what I am trying to do with lambda expression and map function?

like image 696
Antoni4 Avatar asked Dec 01 '22 20:12

Antoni4


2 Answers

Yes, it is:

map (\(x,y) -> (f1 x, f2 y)) list

On the lefthand side of the arrow in the lambda expession, we have the pattern (x,y) to match the tuples in your list. On the righthand side, we write (f1 x, f2 y) to create a new tupel, where the first value is f1 applied to x and the second value is f2 applied to y.

like image 80
felix-eku Avatar answered Dec 04 '22 02:12

felix-eku


An alternative solution would be to just

map (f1 *** f2) list

This is using the fact that Control.Arrow provides the (***) operator, which says that

f *** g = \(x, y) -> (f x, g y)
like image 29
kqr Avatar answered Dec 04 '22 01:12

kqr