Home > Net >  Comparing tuples in haskell
Comparing tuples in haskell

Time:09-27

I was just writing a function that would take in an input of a tuple where the first element would be a string and the second element would be a number. So something like (String, Int). This function was supposed to compare the "Int" value to check if it was bigger or less than a certain value. Just playing around with it, I realised that the following definition for the function works.

check :: (String, Int) -> Grade
check (course, mark) 
    | (course, mark) < (course, 50) = Fail
    | otherwise = Pass

This function seems to work as it checks the integer values. But I don't understand why this works? What is happening to the String in the tuple? How is the string getting compared against it self? I would appreciate if someone could help me understand what is going on.

CodePudding user response:

The definition of < for tuples is equivalent to the following:

instance (Ord a, Ord b) => Ord (a,b) where
  (x,y) < (x',y')
   | x<x'       = True
   | x==x'      = y<y'
   | otherwise  = False

This is called lexicographic ordering.

In your code, you are trivially always in the x==x' branch, because course==course holds (for finite strings, at least). It is an unnecessary comparison, better and equivalent would be to just compare the mark directly, and not even match on course:

check :: (String, Int) -> Grade
check (_, mark) 
    | mark < 50  = Fail
    | otherwise  = Pass
  • Related