Haskell Program to calculate the sum of all even numbers


This tutorial will help us in calculating the sum of all even numbers. Haskell uses a functional programming paradigm, which means that it uses functions to transform data, rather than using loops and variables to keep track of state changes. There are different ways to calculate the sum of all even numbers between 1 and 100 in Haskell.

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 list comprehension [x | x <- [1..100], x mod 2 == 0] is generating a list of even numbers between 1 and 100. The x <- [1..100] part is defining the range of numbers to iterate over, and the x mod 2 == 0 is the predicate that filters out the even numbers. The inbuilt function then takes this list as input and returns the sum of all the numbers in the list.

  • Step 3 − The print function is used to display the result to the console.

Example 1: Using List Comprehension

In This method , the list comprehension is used to generate a list of all even numbers between 1 and 100 (inclusive), and then uses the sum function to calculate the sum of those numbers. The result is then printed to the console using print.

main :: IO()
main = print (sum [x | x <- [1..100], x `mod` 2 == 0])

Output

2550

Example 2: Using foldl Function

In this example, the binary function is (+), which takes the current accumulator and the current element of the list and returns the sum of the two. The initial accumulator value is 0, and the list of values is the list of even numbers between 1 and 100. The foldl function starts with the initial accumulator value and applies the binary function to it and the first element of the list, then it takes the result and applies the function to it and the second element of the list and so on, until the entire list is processed.

main :: IO()
main = print (foldl (+) 0 [x | x <- [1..100], x `mod` 2 == 0])

Output

2550

Example 3: Using Recursion

This example uses recursion to iterate over the list of numbers between 1 and 100 and add the even numbers together. The sumEven function is defined as a recursive function that takes a list of integers as input and returns an integer.

sumEven :: [Integer] -> Integer
sumEven [] = 0
sumEven (x:xs) = if even x then x + sumEven xs else sumEven xs
main :: IO()
main = print (sumEven [1..100])

Output

2550

Conclusion

There are different ways to calculate the sum of all even numbers between 1 and 100 in Haskell, i.e., 2550. In Haskell, the sum of all even numbers between 1 and 100 can be calculated by using list comprehension, by using foldl function or by using recursion.

Updated on: 19-Jan-2023

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements