user3358850
user3358850

Reputation: 129

Addition in tuple list

I'm tring to write a function called maxTotal which will take a list of tuples as a parameter, where each tuple in the list consists of three Ints. I need to find the tuple whose total (the sum of the 3 integers in the tuple) is greatest and return that total.

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

This is what I have:

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)

My tuplesum works but I keep getting errors saying "parse error on input ‘=’"

Upvotes: 0

Views: 84

Answers (1)

Aleph0
Aleph0

Reputation: 6084

You can try this:

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)

Or if you like it even shorter:

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])

If you don't like Maybe you can use:

import Data.List

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

It already gives an error for the empty list.

Upvotes: 1

Related Questions