Reputation: 2227
I have a list of tuples, for example:
[(1,2), (3,4), (5,6)]
Now I have to write function which sum up the first an second element of each tuple and create a list of these values.
For the example above it should be:
[3, 7, 11]
This should be done with use of list comprehension. It's not allowed to use functions like map, filter and contact.
Any ideas how I could access the elements of the tuple in the list?
Upvotes: 0
Views: 4391
Reputation: 30237
Let's do it without list comprehensions, using functions from the Prelude:
map (uncurry (+)) [(1,2), (3,4), (5,6)]
-- Result: [3, 7, 11]
How does this work? Let's consider the types:
(+) :: Num a => a -> a -> a
uncurry :: (a -> b -> c) -> (a, b) -> c
map :: (a -> b) -> [a] -> [b]
As you may already know, in Haskell, the normal way of doing multi-argument functions is by **currying* them. The type of (+)
reflects this: conceptually it takes one argument and produces a function that then takes the "second" argument to produce the final result.
uncurry
takes such a curried two-argument function and adapts it to work on a pair. It's trivial to implement:
uncurry :: (a -> b -> c) -> (a, b) -> c
uncurry f (a, b) = f a b
Funnily enough, the uncurry
function is curried, so its partial application uncurry (+)
has type Num a => (a, a) -> a
. This would then be a function that takes a pair of numbers and adds them.
And map
simply applies a function to every element of a list, collecting the individual results into a list. Plug them all together and that's a solution.
Upvotes: 2
Reputation: 21757
Try this:
[ x + y | (x,y) <- yourlist]
The trick is representing the two elements in a tuple from your input list as x
and y
and then dealing with them as needed.
Upvotes: 4