我正在编写一个函数,它总结了元组列表的元素,如下所示:
sumAll [(2,4,11), (3,1,-5), (10,-3,6)] = (15,2,12)
我确实有这个:
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)
然而编译器抱怨:
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)
表达式相同(map(snd)l)。
如果我删除' c'它起作用的函数定义中的参数。 像这样:
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)
我的问题,如果可能的话:
答案 0 :(得分:4)
考虑如何定义fst
,snd
和trd
。如果您使用fst
中的Prelude
,则其类型为fst :: (a, b) -> a
,但不适用于3元组。