In Haskell, the sum of n numbers can be calculated using recursion with user defined function, or by using tail or fold recursive approaches. In this case, the binary function is (+) and the initial value is 0, so it add the elements of the list one by one starting from the right side. The foldr function takes a binary function, a list, and applies the binary function to the elements of the list, folding the list up into a single value. In this example, the foldr function is used to find the sum of elements in the list. The function uses an accumulator to keep track of the sum and avoid stack overflow. In all other cases, the function returns the result of calling sumOfN' with the arguments acc + n and n-1. The base case is when n equals 0, in which case the function returns the value of acc. In this example, a tail-recursive function sumOfN' is defined that takes in two arguments: an accumulator acc and n. This is done using the sum_n function recursively. If the list is not empty, it takes the first element (x) and adds it to the sum of the rest of the list (xs). ![]() In this example, the function sum_n takes a list of integers as an input and uses a pattern matching to check if the list is empty. Step 4 − The resultant sum of the numbers is printed to the console using ‘print’ function, after the sum_n function is called. It will hold the list of numbers whose sum is to be computed. Step 3 − The variable named, “numbers” is being initialized. We are building a multi skilled Dev Team, from different technology stack backgrounds, we want talented Devs who will help us explore different technology ideas and solutions, the team already. In the main function, we create a list of numbers and pass it to the sum_n function to find the sum. The main() function has whole control of the program. ![]() Step 2 − Program execution will be started from main function. Step 1 − The recursive sum_n function is defined as, And in the third example, we are going to use (sumOfN''' xs = foldr (+) 0 xs) function. In the first example we are going to use base case, (sum_n = 0) and recursive case, (sum_n (x:xs) = x + sum_n xs)) and in second example, we are going to use, tail-recursion. In Haskell, we can find Sum of N Numbers by using recursion, tail-recursion and fold-recursion.
0 Comments
Leave a Reply. |