sumTriplos :: (Num a, Num b, Num c) => [(a,b,c)] -> (a,b,c)
我想要一个将列表中所有三元组求和并返回一个具有所有总和的函数,如下所示:
sumTriplos [(2,4,11), (3,1,-5), (10,-3,6)] = (15,2,12)
代码:
extractFirst :: (a, b, c) -> a
extractFirst (a,,) = a
extractSirst :: (a, b, c) -> a
extractSirst (,a,) = a
extractTirst :: (a, b, c) -> a
extractTirst (,,a) = a
sumTriplos :: (Num a, Num b, Num c) => [(a,b,c)] -> (a,b,c)
sumTriplos [(a,b,c)] = (a,b,c)
sumTriplos (h:a:t) = sumTriplos ((extractFirst h)+(extractFirst a),(extractSirst h)+(extractSirst a),(extractTirst h)+(extractTirst a)) t
答案 0 :(得分:1)
简单的折叠?
sumTriplos = foldr sumt (0,0,0)
where sumt (x,y,z) (a,b,c) = (x+a,y+b,z+c)
答案 1 :(得分:1)
sumTriplos
带有一个参数,一个列表。但是,您的递归调用具有两个两个参数,即前两个元组和其余元组的和。您想将第一个元组添加到其余元组的递归调用的结果中。
而不是(缩写为extract*
函数)
sumTriplos (h:a:t) = sumTriplos ((ef h + ef a), (es h + es a), (et h + et a)) t
您想要类似的东西
sumTriplos (h:t) = (ef h + ef r, es h + es r, et h + et r)
where r = sumTriplos t