Haskell Program to get the predecessor of an integer number using library function


In Haskell, we can use library function like pred, subtraction and fromMaybe to get the predecessor of an integer number. In the first example, we are going to use (pred number) function and in the second example, we are going to use subtraction while in third example, we are going to use (fromMaybe 0 (predMaybe x)) 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. It calls the pred function with the value and prints its predecessor to the console.

  • Step 2 − The variable named, “number” is being initialized. It will hold the value to compute its predecessor value.

  • Step 3 − The resultant predecessor value is printed to the console using ‘putStrLn’ statement after calling the function.

Example 1

In this example, we are going to see that how we can get the predecessor value of an integer number. This can be done by using pred function.

main :: IO ()
main = do
   let number = 5
   let predecessor = pred number
   putStrLn (show predecessor)

Output

4

Example 2

In this example, we are going to see how we can get the predecessor value of an integer number. This can be done by using mathematical subtraction of a unit number from the given number.

main :: IO ()
main = do
   let x = 5
   print (x - 1)

Output

4

Example 3

In this example, we are going to see that how we can get the predecessor value of an integer number. This can be done by using pattern matching.

pred' :: Int -> Int
pred' 0 = error "Cannot find predecessor of 0"
pred' x = x - 1

main :: IO ()
main = do
   let x = 5
   print (pred' x)

Output

4

Example 4

In this example, we are going to see that how we can get the predecessor value of an integer number. This can be done by using fromMaybe function.

import Data.Maybe

main :: IO ()
main = do
   let x = 5
   print (fromMaybe 0 (predMaybe x))

predMaybe :: Int -> Maybe Int
predMaybe x = if x > 0 then Just (x - 1) else Nothing

Output

4

Conclusion

In Haskell, there are various ways to find the predecessor of a given number. Some common ways include using built-in library functions like pred from the Prelude library, subtracting 1 from the number, using the mod function, or writing a custom function that uses pattern matching or conditional statements to find the predecessor.

Updated on: 13-Mar-2023

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements