Reputation:
I'm writing a function that sums the elements of a list of tuples like this:
sumAll [(2,4,11), (3,1,-5), (10,-3,6)] = (15,2,12)
I do have this:
sumAll :: (Num a, Num b, Num c) => [(a,b,c)] -> (a,b,c)
sumAll l = (foldr (+) 0 as, foldr (+) 0 bs, foldr (+) 0 cs)
where trd (a,b,c) = c
as = (map (fst) l)
bs = (map (snd) l)
cs = (map (trd) l)
However the compiler complains:
Couldn't match type `(a, b, c)' with `(b1, b0)'
Expected type: [(b1, b0)]
Actual type: [(a, b, c)]
Relevant bindings include
as :: [b1] (bound at ficha3.hs:22:22)
cs :: [c] (bound at ficha3.hs:24:22)
l :: [(a, b, c)] (bound at ficha3.hs:20:12)
sumAll :: [(a, b, c)] -> (a, b, c) (bound at ficha3.hs:20:1)
In the second argument of `map', namely `l'
In the expression: (map (fst) l)
And the same for the expression (map (snd) l).
If I delete 'c' parameters from function definition it Works. Like this:
sumAll :: (Num a, Num b) => [(a,b)] -> (a,b)
sumAll l = (foldr (+) 0 as, foldr (+) 0 bs)
where as = (map (fst) l)
bs = (map (snd) l)
My questions, if possible:
Upvotes: 0
Views: 109
Reputation: 1639
Consider how your fst
, snd
, and trd
are defined. If you are using fst
from Prelude
, then it has a type of fst :: (a, b) -> a
, which does not work for 3-tuples.
Upvotes: 4