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


In Haskell, we can get the the successor of an integer number using library function like succ, addition and fromMaybe function. In the first example, we are going to use (succ number) function and in the second example, we are going to use addition while in third example, we are going to use (fromMaybe 0 (succMaybe 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 succ function with the value and prints its successor to the console.

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

  • Step 3 − The resultant successor 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 successor value of an integer number. This can be done by using succ function.

main :: IO ()
main = do
   let number = 5
   let successor = succ number
   putStrLn (show successor)

Output

6

Example 2

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

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

Output

6

Example 3

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

succ' :: Int -> Int
succ' 0 = error "Cannot find successor of 0"
succ' x = x + 1

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

Output

6

Example 4

In this example, we are going to see that how we can get the successor 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 (succMaybe x))

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

Output

6

Conclusion

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

Updated on: 13-Mar-2023

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements