Haskell Program to check the given number is an EVEN number using library function

In Haskell, we can use library function like mod, even and quot to check whether, the given number is an EVEN number or not. In this article we are going to have examples that are using n mod 2 == 0 even function as well as n quot 2 == 0 function.

Algorithm

• Step 1 − The isEven function is defined using mod function as, isEven n = n mod 2 == 0.

• 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. It calls the isEven function with the value to check if it is Even or not and prints the result.

• Step 3 − The variable named, “num” is being initialized. It will hold the value to check if the value is even or not.

• 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 an even or not. This can be done by using mod function.

isEven :: Integral a => a -> Bool
isEven n = n mod 2 == 0

main :: IO ()
main = do
let num = 4
if isEven num
then putStrLn "The number is even."
else putStrLn "The number is odd."


Output

The number is even.


Example 2

In this example, we are going to see that how we can check if the given number is an even or not. This can be done by using mod function This uses a guard to check if the remainder of the input divided by 2 is equal to 0, which indicates that the number is even.

isEven :: Integral a => a -> Bool
isEven n
| n mod 2 == 0 = True
| otherwise = False

main :: IO ()
main = do
let num = 5
if isEven num
then putStrLn "The number is even."
else putStrLn "The number is odd."


Output

The number is odd.


Example 3

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

isEven :: Integral a => a -> Bool
isEven = even

main :: IO ()
main = do
let num = 4
if isEven num
then putStrLn "The number is even."
else putStrLn "The number is odd."


Output

The number is even.


Example 4

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

isEven :: Integral a => a -> Bool
isEven n = n quot 2 == 0

main :: IO ()
main = do
let num = 5
if isEven num
then putStrLn "The number is even."
else putStrLn "The number is odd."


Output

The number is odd.


Conclusion

To check if the given number is an even or not, we can use the mod, even or quot functions in Haskell. It can also be checked using if-else statement. Even numbers are integers that are divisible by 2. In other words, an even number is any number that can be written in the form 2n, where n is an integer.

Updated on: 13-Mar-2023

417 Views