在元组列表中添加

时间:2017-04-24 11:25:33

标签: algorithm haskell tuples

我想写一个名为maxTotal的函数,它将一个元组列表作为参数,其中列表中的每个元组由三个Int组成。我需要找到元组的总数(元组中3个整数的总和)最大并返回总数。

example:
*Main> maxTotal [(1,2,3),(7,4,2),(5,5,1)]
13
*Main> maxTotal [(1,2,3),(5,5,1),(3,15,0)]
18
*Main> maxTotal [(3,3,3)]
9

这就是我所拥有的:

tuplesum :: (Num a) => [(a,a,a)] -> [a] 
tuplesum  [] = []
tuplesum  ((a,b,c):xs) = (a+b+c) : tuplesum  xs
maxTotal::(Num a) =>[(a,a,a)]->a
maxTotal[]=error"empty list"
maxTotal tuplesum (head : tail) = max head (maxTotal tail)

我的tuplesum工作,但我一直收到错误说“输入'解析错误='”

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

import Data.List

tuplesum :: (Num a) => [(a,a,a)] -> [a] 
tuplesum x = [a+b+c|(a,b,c)<-x]
maxTotal::(Num a, Ord a) =>[(a,a,a)]->Maybe a
maxTotal [] =Nothing
maxTotal x = Just (maximum $ tuplesum x)

或者如果你喜欢它更短:

import Data.List

maxTotal::(Num a, Ord a) =>[(a,a,a)]->Maybe a
maxTotal [] = Nothing
maxTotal x = Just (maximum [a+b+c|(a,b,c)<-x])

如果您不喜欢,可以使用:

import Data.List

maxTotal::(Num a, Ord a) =>[(a,a,a)]->a
maxTotal x = maximum [a+b+c|(a,b,c)<-x]

它已经为空列表提供了错误。