Haskell Program to read the height of a person and the print person is taller, dwarf, or average height person


This tutorial will help us in reading the height of a person and printing if the person is taller, dwarf or average height person on being compared. The height value (in centimeters) is passed as argument to the function defined and then the height is being compared with the condition defined in Haskell. And the final output is displayed.

Algorithm

  • Step 1 − Program execution will be started from main function. The main() function has whole control of the program.

  • Step 2 − Create user defined function to perform the task

  • Step 3 − The if-else statement is defined over the height as if height > 180, the person is tall; else if height < 150, the person is dwarf ; else the person has average height.

  • Step 4 − The final output is displayed after comparing the height value, by using ‘putStrLn’ statement.

Using if-else Statement

In this example, we will use if-else statement to check the value of height and prints the appropriate message.

Example 1

main :: IO ()
main = do
  let height = 165
  if height > 180
     then putStrLn "You are a tall person."
  else if height < 150
     then putStrLn "You are a dwarf."
  else putStrLn "You are an average height person."

Output

You are an average height person.

Using User-defined Function

In this example, the heightDescription function is used to determine the description of the person's height based on their input. The heightDescription function uses guards to check the value of the input against various conditions, and returns the appropriate string based on the input.

Example 2

main :: IO ()
main = do
  let height = 185
  putStrLn (heightDescription height)

heightDescription :: Float -> String
heightDescription height
   | height > 180 = "You are a tall person."
   | height < 150 = "You are a dwarf."
   | otherwise = "You are an average height person."

Output

You are a tall person.

Using Pattern Matching

In this example, the pattern matching is used to determine the description of the person's height based on their input.

Example 3

main :: IO ()
main = do
  let height = 145
  putStrLn (heightDescription height)
heightDescription :: Float -> String
heightDescription height = 
    case height of
        h | h > 180  -> "You are a tall person."
        h | h < 150  -> "You are a dwarf."
        _            -> "You are an average height person."

Output

You are a dwarf.

Conclusion

In Haskell, there are various ways to read the height of a person and then predict its height description. To check the same we can use, if-else statement, user-defined heightDescription function or by using pattern matching. The height value is passed as an argument to these functions and then the height description of the person is displayed as output.

Updated on: 23-Jan-2023

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements