简体   繁体   English

尾调用平方和递归 function 球拍

[英]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.我正在尝试编写尾调用递归 function 来查找列表中的平方和。 I have some code that works but currently, it is a non-tail-call function. How would I change it to be tailed?我有一些有效的代码,但目前它是一个非尾调用 function。我如何将其更改为尾调用?

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

The usual way to convert a function that accumulates results to tail recursion is by moving the accumulator into a parameter.将累加结果的 function 转换为尾递归的常用方法是将累加器移动到参数中。 In the code below, the sum parameter accumulates the sums of squares.在下面的代码中, sum参数累加平方和。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM