Haskell Program to compare numbers and strings using library function


In Haskell, we will compare numbers and strings using library function using compare, min and max functions. Also, by using Eq and Ord typeclasses. In the first example we are going to use (compare num1 num2 and compare str1 str2) function and in the second example, we are going to use (max num1 num2 and min str1 str2) function. And in third example, we are going to use (num1 == num2) function along with (num1 /= num2) typeclasses.

Algorithm

  • Step 1 − The Data.Ord library is imported, which contains the compare function.

  • Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. The main function then defines two variables num1 and num2 as integers and two variables str1 and str2 as strings and prints the result on comparing.

  • Step 3 − The variables named, “num1”, “num2”, “str1” and “str2” are being initialized. It will hold the numbers and strings respectively, that will be compared.

  • Step 4 − The compared result is printed to the console using ‘print’ function after the compare function is called.

Example 1

In this example, we are going to see that how we can compare the numbers and strings using compare function.

import Data.Ord (compare)

main :: IO ()
main = do
      let num1 = 5
          num2 = 10
          str1 = "hello"
          str2 = "world"

      print (compare num1 num2) 
      print (compare str1 str2)

Output

LT
LT

Example 2

In this example, we are going to see that how we can compare the numbers and strings using min and max functions.

main :: IO ()
main = do
      let num1 = 5
          num2 = 10
          str1 = "hello"
          str2 = "world"

      print (max num1 num2)
      print (min str1 str2)

Output

10
"hello"

Example 3

In this example, we are going to see that how we can compare the numbers and strings by using Eq and Ord typeclasses.

main :: IO ()
main = do
      let num1 = 5
          num2 = 10
          str1 = "hello"
          str2 = "world"

      print (num1 == num2)  
      print (num1 /= num2)
      print (str1 <= str2)  
      print (str1 >= str2)

Output

False
True
True
False

Conclusion

In Haskell, to compare the numbers and strings we can use compare, min and max functions and Eq and Ord typeclasses.

Updated on: 13-Mar-2023

652 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements