Haskell Program to check a given number is finite or not


In Haskell, we can use isIEEE, isInfinite and isNaN functions to check whether a given number is finite or not. In the first example we are going to use (isIEEE n) function with if-else statement and in the second example, we are going to use (isInfinite n) function. And in third example, we are going to use (isNaN) function along with (isInfinite n) function.

Algorithm

  • Step 1 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do.

  • Step 2 − The variable named, “n” is being initialized. It will hold the value to check if the value is finite or not.

  • Step 3 − The internal function is called by passing a number as argument to it.

  • Step 4 − The result is printed to the console using ‘putStrLn’ statement after checking the integer.

Example 1

In this example, we are going to see that how we can check if the given number is finite or not. This can be done by using isIEEE function.

main :: IO ()
main = do
   let n = 205678
   if isIEEE n
      then putStrLn $ show n ++ " is a finite number."
      else putStrLn $ show n ++ " is not a finite number."

Output

205678.0 is a finite number.

Example 2

In this example, we are going to see that how we can check if the given number is finite or not. This can be done by using isInfinite function. This function is used after importing Data.Functor.Constant module.

import Data.Functor.Constant

main :: IO ()
main = do
   let n = 28567
   if isInfinite n
      then putStrLn $ show n ++ " is not a finite number."
      else putStrLn $ show n ++ " is a finite number."

Output

28567.0 is a finite number.

Example 3

In this example, we are going to see that how we can check if the given number is finite or not. This can be done by using isInfinite and isNaN function with if-else statements. This function is used after importing Data.Functor.Constant module.

import Data.Functor.Constant

main :: IO ()
main = do
   let n = 28567
   if isInfinite n
      then putStrLn $ show n ++ " is not a finite number."
      else if isNaN n
         then putStrLn $ show n ++ " is not a number."
         else putStrLn $ show n ++ " is a finite number."

Output

28567.0 is a finite number.

Conclusion

A finite number is a number that can be represented in a finite amount of memory or on a finite number of digits. And an infinite number is a number that cannot be represented in a finite amount of memory or on a finite number of digits. In Haskell, a function returns True if a given number is finite and False if the number is infinite. To check if the given number is finite or not, we can use the is IEEE function or isInfinite function along with isNaN function. It can also be checked using if-else statement.

Updated on: 13-Mar-2023

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements