Haskell Program to Display Armstrong Numbers Between Intervals Using Function


Haskell has functions like higher order and filter, that can be used for getting the Armstrong number between two given internvals. In the first example we are going to use (isArmstrong and armstrongInRange function with higher order) and in the second example, we are going to use (filter isArmstrong [a..b]) function.

Algorithm

  • Step 1 − The user-defined isArmstrong function is defined.

  • 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.

  • Step 3 − The variables named, “lower” and “upper” are being initialized. It will hold the range between which the armstrong numbers is to be printed.

  • Step 4 − The resultant armstrong numbers under the defined range is printed to the console using ‘print’ function after the function is called.

Example 1

In this example, we are going to see that how we can display armstrong numbers between two interval by using higher order function.

import Data.List (find)

isArmstrong :: Integer -> Bool
isArmstrong n = n == sum (map (^ len) digits)
   where
      digits = map (\x -> read [x] :: Integer) (show n)
      len = length digits

armstrongInRange'''' :: Integer -> Integer -> [Integer]
armstrongInRange'''' a b = filter (\x -> x == sum (map (^ (length (show x))) (map (\x -> read [x] :: Integer) (show x)))) [a..b]

main :: IO ()
main = do
let lower = 100
let upper = 1000
print (armstrongInRange'''' lower upper)

Output

[153,370,371,407]

Example 2

In this example, we are going to see that how we can display armstrong numbers between two interval by using filter function.

import Data.List (find)

isArmstrong :: Integer -> Bool
isArmstrong n = n == sum (map (^ len) digits)
   where
      digits = map (\x -> read [x] :: Integer) (show n)
      len = length digits

armstrongInRange' :: Integer -> Integer -> [Integer]
armstrongInRange' a b = filter isArmstrong [a..b]

main :: IO ()
main = do
let lower = 100
let upper = 1000
print (armstrongInRange' lower upper)

Output

[153,370,371,407]

Conclusion

Armstrong numbers are relatively rare and are only found in small numbers. They are named after Michael F. Armstrong who is credited with discovering them.

In Haskell, to display the armstrong numbers between intervals we can use higher order function and filter function.

Updated on: 13-Mar-2023

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements