Question: In c Language Recall that a function is tail recursive if its recursive call is the last operation in the function. A tail recursive function
In c Language
Recall that a function is tail recursive if its recursive call is the last operation in the function. A tail recursive function can be automatically converted by a compiler to use iteration, making it faster We have seen that a function can be made tail recursive by using a helper function, which we will call as accumulator, as in the following example. Original: (define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1))) )) Tail recursive: (define (fact-accumulator n factpartial) (if (= n 0) factpartial (fact-accumulator (- n 1) (* n factpartial)) )) (define (factorial n) (fact-accumulator n 1)) We can write the tail recursive function also as follows. (define (factorial n) (letrec ((fact-accumulator (lambda (n factpartial) (if (= n 0) factpartial (fact-accumulator (- n 1) (* n factpartial)) ) ) (fact-accumulator n 1) )) a) Write a recursive function sum-of-factorials-of-elements that takes a list, and returns the sum of factorials of the elements of the list. Call the factorial function defined above. For example (sum-of-factorials-of-elements '(1 3)) should return (+ (factorial 1) (factorial 3)) => 7 b) Turn the above function into a tail recursive function. c) Step through the evaluation of the original and tail recursive functions for the following call. Use the result of factorial directly. (sum-of-factorials-of-elements (3 2 5 1 4))
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
