比较元组和元组列表

问题描述

我必须将一个元组一个元组列表进行比较,如果整数小于列表中的任何元组,则返回True。就像我有superM ("Tomato",10,5) [("Potato",5,6),("Orange",11,6)]会返回True,因为单独的元组(“ Tomate”,10,5)中的整数比列表中的元组(“ Orange”,11,6)小,但是如果我有superM ("Melon",6) [("Potato",6)]将返回False。

我尝试

superM :: (String,Int,Int) -> [(String,Int)] -> Bool
superM (s,a,b) ((_,c,d):xs)
  | a < c && b < d = True
  |otherwise =  superM (s,b) xs  

但是当它假定返回False并且我不知道为什么时不起作用?

注意:字符串对这个问题无关紧要,我必须忽略它。

解决方法

您没有为空列表定义基本情况。因此,如果没有元素匹配,最终列表将被耗尽,然后空列表将不匹配。因此,您可以为空列表添加一条规则:

superM :: (String,Int,Int) -> [(String,Int)] -> Bool
superM _ [] = False
superM (s,a,b) ((_,c,d):xs)
  | a < c && b < d = True
  |otherwise =  superM (s,b) xs

我们可以利用逻辑或摆脱警卫:

superM :: (String,d):xs) = a < c && b < d || superM (s,b) xs

但是我们也可以使用any :: Foldable f => (a -> Bool) -> f a -> Bool函数来使其与任何Foldable一起使用:

superM :: (Foldable f,Ord x,Ord y) => (a,x,y) -> f (b,y) -> Bool
superM (_,b) = any p
    where p (_,d) = a < c && b < d