Question: Convert the iterative function below provided as a loop into a tail recursive version. Use of var/loops is forbidden. Here is text code and I
Convert the iterative function below provided as a loop into a tail recursive version. Use of var/loops is forbidden.
Here is text code and I attached the picture.of it
def seriesSummationUsingLoop(a: Int, b: Int, func: Int => Int): Int = { var acc = 0 var i = a while (i
import scala.annotation.tailrec
@tailrec def tailRecursiveSummationHelper(b: Int, func: Int => Int, i: Int, acc: Int): Int = { assert(i
def tailRecursiveSummation(a: Int, b: Int, func: Int => Int) = { tailRecursiveSummationHelper(b, func, a, 0) }
//BEGIN TEST val square = (i: Int) => i*i val ident = (i:Int) => i assert(tailRecursiveSummation(1, 10, ident) == 55, "summation of 1 to 10 is 55") assert(tailRecursiveSummation(1, 4, square) == 30, "summation of 1^2+2^2+3^2+4^2 is 30") assert(tailRecursiveSummation(4, 4, square) == 16, "summation of 4^2 is 16") assert(tailRecursiveSummation(-1, 1, ident) == 0, "summation of -1+0+1 is 0")
passed(8) //END TEST

Part A Convert the iterative function below provided as a loop into a tail recursive version. [ ]: def seriesSummationUsing Loop(a: Int, b: Int, func: Int => Int): Int = { var acc = 0 var i = a while (i Int, i: Int, acc: Int): Int = { assert(i Int) = { tailRecursiveSummationHelper (b, func, a, 0) } nl ]://BEGIN TEST val square = (i: Int) => i*i val ident = (i: Int) => i assert(tailRecursive Summation(1, 10, ident) == 55, "summation of 1 to 10 is 55") assert(tailRecursiveSummation(1, 4, square) 30, "summation of 1^2+2^2+3^2+4*2 is 30") assert(tailRecursiveSummation (4, 4, square) == 16, "summation of 4*2 is 16") assert(tailRecursiveSummation(-1, 1, ident) == 0, "summation of -1+0+1 is 0") passed (8) //END TEST Part A Convert the iterative function below provided as a loop into a tail recursive version. [ ]: def seriesSummationUsing Loop(a: Int, b: Int, func: Int => Int): Int = { var acc = 0 var i = a while (i Int, i: Int, acc: Int): Int = { assert(i Int) = { tailRecursiveSummationHelper (b, func, a, 0) } nl ]://BEGIN TEST val square = (i: Int) => i*i val ident = (i: Int) => i assert(tailRecursive Summation(1, 10, ident) == 55, "summation of 1 to 10 is 55") assert(tailRecursiveSummation(1, 4, square) 30, "summation of 1^2+2^2+3^2+4*2 is 30") assert(tailRecursiveSummation (4, 4, square) == 16, "summation of 4*2 is 16") assert(tailRecursiveSummation(-1, 1, ident) == 0, "summation of -1+0+1 is 0") passed (8) //END TEST
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
