How to find sum of list of numbers in Haskell
Haskell is a functional programming language known for its strong type system and lazy evaluation. In Haskell, we can calculate the sum of a list using a recursive function that repeatedly adds each element to a variable until we encounter an empty list, or we can use a built-in sum function to find the sum of the list.
Custom function
We will construct our own recursive function to explore the problem and examine its code structure.
Approach
We can use a very basic approach to solve this problem. Here are the steps you need to follow to be able to find the sum of a list:
Define a function that accepts a list.
In the recursive case, calculate the sum by adding the current element to the sum of the rest of the list, whereas in the base case, an empty list will return the sum as 0.
Once the function reaches the base case, it effectively "calls back" to the previous recursive step, where the sum of each element was accumulated. This completes the recursion process, and the final sum is returned as the result of the function.
Code
The function sumList calculates the sum of a list using recursion, adding the current element to the sum of the rest of the list until it reaches the base case of an empty list, where it returns 0. This process effectively computes the sum of all elements in the list.
-- Function to calculate the sum of a list using recursionsumList :: Num a => [a] -> asumList [] = 0 -- Base case: empty list has a sum of 0sumList (x:xs) = x + sumList xs -- Recursive case: add current element to the sum of the restmain :: IO ()main = dolet numbers = [1, 2, 3, 4, 5]let result = sumList numbersputStrLn $ "Sum of the list: " ++ show result
Line 2: The
sumListfunction signature indicates that it takes a list of elements of typea(belonging to theNumclass) and returns a single value of the same typea. TheNum a =>part is a type constraint, ensuringamust be a numeric type likeInt,Integer, orFloatfor the function to work.Line 3: When the input list is empty (represented by
[]), the function returns0. This is the terminating condition for the recursion. When the list is empty, there are no elements left to add, so the sum is 0.Line 4: This is the recursive case of the
sumListfunction, it calculates the sum by adding the current elementx(the head of the list) to the sum of the rest of the list obtained through recursive calls withsumList xs, which represents the rest of the list.
Built-in sum function
The sum function helps us to find the sum of a list directly in Haskell. It uses the same recursive approach which we have discussed above to calculate the sum.
Code
-- Example usage of sum functionmain :: IO ()main = dolet numbers = [1, 2, 3, 4, 5]let result = sum numbersprint result
Complexity
The custom and in-built functions use a recursive approach, so they have similar complexities. They have a time complexity of
Free Resources