rafro4
rafro4

Reputation: 65

How do you use pattern matching with lists of tuples in Haskell?

I've been trying to write a function that takes a list of tuples (in my case, three Int values within the tuple) and returns the maximum sum of any of the tuples in the list.

This is my current attempt at doing so:

type Triples = [(Int, Int, Int)]
maxTotal :: Triples -> Int
maxTotal [] = error "ERROR: NO TUPLES"
maxTotal ((x,y,z):rest)
  | sumTriple x y z > maxTotal rest = sumTriple x y z
  | otherwise = maxTotal rest

sumTriple :: Int -> Int -> Int -> Int
sumTriple x y z = x + y + z

However, every time I run this function, I end up with my error output... Is Haskell treating my input list of tuples as an empty list or am I cycling through to the end of the list in my "otherwise" guard then reaching the error?

Upvotes: 0

Views: 1045

Answers (1)

rafro4
rafro4

Reputation: 65

Turns out my definitions for maxTotal were incomplete. All I had to add was this:

maxTotal [(x,y,z)] = x + y + z

Case closed.

Upvotes: 1

Related Questions