Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tail-Call sum-of-squares-recursive function Racket

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)))
        )))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading