Home > Mobile >  Tail-Call sum-of-squares-recursive function Racket
Tail-Call sum-of-squares-recursive function Racket

Time:02-25

I am trying to write a tail-call recursive function to find the sum of squares that are in a list. I have some code that works but currently, it is a non-tail-call function. How would I change it to be tailed?

(define sum-of-squares
  (lambda (lst)
    (if (null? lst)
        0
        (  (* (car lst) (car lst)) (sumsquares (cdr lst)))
        )))

CodePudding user response:

The usual way to convert a function that accumulates results to tail recursion is by moving the accumulator into a parameter. In the code below, the sum parameter accumulates the sums of squares.

(define sum-of-squares
  (lambda (lst)
    (define recursive-sos
      (lambda (lst sum)
        (if (null? lst)
            sum
            (recursive-sos (cdr lst)
                           (  (* (car lst) (car lst)) 
                              sum)))))
    (recursive-sos lst 0)))
  • Related