Question: Scheme is the programming language should it be done Recall that a function is tail recursive if its recursive call is the last operation in

 Scheme is the programming language should it be done Recall that

Scheme is the programming language should it be done

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) )) Consider the following recursive function that computes the sum of squares of the first n numbers. (define sum-of-squares (lambda (n) (if (= n 0) 0 (+ (sum-of-squares (- n 1)) (* n n))))) a) Write a tail recursive version for the same function using letrec. b) Then, step through the evaluation of the original and tail recursive functions for (sum-of-squares 5). Write briefly about your observations

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!