让 Racket 中的循环代码。递归阶乘

use*_*199 4 loops racket

考虑:

(define (factorial x)
  (let loop ((x x)
             (acc 1))
    (if (zero? x)
        acc
        (loop (sub1 x) (* x acc)))))
Run Code Online (Sandbox Code Playgroud)

我不明白如何让这里工作。此外,我不明白这段代码。

soe*_*ard 5

您的示例与

(define (factorial x)
  (define (loop x acc)
    (if (zero? x)
        acc
        (loop (sub1 x) (* x acc))))
   (loop x 1))
Run Code Online (Sandbox Code Playgroud)

它的工作原理与

  (define (factorial x)
    (loop x 1))

  (define (loop x acc)
    (if (zero? x)
        acc
        (loop (sub1 x) (* x acc))))
Run Code Online (Sandbox Code Playgroud)

要查看程序如何工作,最好的建议是使用 DrRacket 中的步进器。由于步进器必须以“中级”教学语言运行,因此将此版本(注意最后一个示例)粘贴到 DrRacket 中。选择“中级”教学语言,然后单击步进按钮。

(define (factorial x)
  (loop x 1))

(define (loop x acc)
  (if (zero? x)
      acc
      (loop (sub1 x) (* x acc))))

(factorial 3)
Run Code Online (Sandbox Code Playgroud)

另请参阅此问题以获取显示步进器的图像:Scheme 中的斐波那契数列