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?
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
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With