[英]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. 我一直在尝试编写一个函数,该函数接受一个元组列表(在本例中为元组内的三个Int值),并返回列表中任何元组的最大和。
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? 但是,每次运行此函数时,我都会得到错误输出...是Haskell将元组的输入列表视为一个空列表,还是我在“否则”的防护中循环到该列表的末尾,然后到达错误?
Turns out my definitions for maxTotal were incomplete. 原来我对maxTotal的定义不完整。 All I had to add was this:
我只需要添加以下内容:
maxTotal [(x,y,z)] = x + y + z
Case closed. 案件结案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.