Reputation: 109
I have to compare a tuple with a list of tuples and returns True if the integers are less than any of the tuples in the list. Like if i have superM ("Tomato",10,5) [("Potato",5,6),("Orange",11,6)]
will return True because the integers in the alone Tuple ("Tomate",10,5) are smaller then the tuple("Orange",11,6) in the list, but if i have superM ("Melon",10,6) [("Potato",5,6),("Orange",11,6)]
will return False.
I try this
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
But doesn't work when it suppose to return False and I don't know why?
Note:The Strings doesn't matter for this problem, i must ignore it.
Upvotes: 1
Views: 82
Reputation: 476537
You did not define a basecase for the empty list. So if no element matches, eventually the list will be exhausted, and then the empty list will not match. You thus can add a rule for the empty list:
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
we can make use of a logical or to get rid of the guards:
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
but we can also use the any :: Foldable f => (a -> Bool) -> f a -> Bool
function to let this work with any 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
Upvotes: 1