簡體   English   中英

將元組與元組列表進行比較

[英]Compare Tuple with a List of Tuples

我必須將元組與元組列表進行比較,如果整數小於列表中的任何元組,則返回 True。 就像如果我有superM ("Tomato",10,5) [("Potato",5,6),("Orange",11,6)]將返回 True 因為單獨元組中的整數 ("Tomate", 10,5) 比列表中的元組 ("Orange",11,6) 小,但是如果我有superM ("Melon",10,6) [("Potato",5,6),("Orange",11,6)]將返回 False。

我試試這個

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

但是當它假設返回 False 時不起作用,我不知道為什么?

注意:字符串與此問題無關,我必須忽略它。

您沒有為空列表定義 basecase。 所以如果沒有元素匹配,最終列表將被耗盡,然后空列表將不匹配。 因此,您可以為空列表添加規則:

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

我們可以利用邏輯或擺脫守衛:

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

但我們也可以使用any :: Foldable f => (a -> Bool) -> fa -> Bool函數來讓它與任何Foldable工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM