Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparing tuples in haskell

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading