iteration - SICP - 我对阶乘迭代过程的递归定义不好吗?

标签 iteration lisp racket factorial sicp

我正在学习 SICP 这本很棒的书。尽管很棒,但它确实是一本难懂的书。我遇到了长尾递归问题,id est,迭代过程的递归定义。 这本书介绍了阶乘的迭代过程:

(define (factorial n)
  (fact-iter 1 1 n))
(define (fact-iter product counter max-count)
  (if (> counter max-count)
      product
      (fact-iter (* counter product)
                 (+ counter 1)
                 max-count)))

我尝试在不看书中示例的情况下采用一种方法。我明白了:

(define (factorial n)
  (factorial-iter n 1 n))

(define (factorial-iter a product counter)
  (if (= counter 0)
      product
      (factorial-iter (- a 1)
                      (* product a)
                      (- counter 1))))     

我的方法在某种意义上是错误的吗?

最佳答案

您的方法没有任何错误,它可以正确计算阶乘,只有一些多余的东西。您可以注意到 acounter 这两个变量始终具有相同的值,因为它们始终以相同的方式更新。所以你可以摆脱其中之一,并以这种方式简化你的功能:

(define (factorial n)
  (factorial-iter n 1))

(define (factorial-iter a product)
  (if (= a 0)
      product
      (factorial-iter (- a 1)
                      (* product a))))

最后,为了安全起见,您可以更改终止测试以查看 a 是否小于或等于 0,这样函数就不会以负参数无限循环:

(define (factorial-iter a product)
  (if (<= a 0)
      product
      (factorial-iter (- a 1)
                      (* product a))))

关于iteration - SICP - 我对阶乘迭代过程的递归定义不好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39335918/

相关文章:

scheme - 计算 Racket BSL 中给定数字的适当除数之和

racket - 多态函数 `car' 无法应用于参数

scheme - 将命令行参数解析为 Racket 中的数字

python - 在 Python 中迭代多个列表项的组合

c - 将 Torvalds 的 "Good Taste"应用于 Fortran 链表

scheme - scheme/racket/中的文件路径

lisp - 作业 : Lisp items that appear more than once in a list

python - 在 Python 中迭代包含在 3d 数组中的 2d 数组

java - 从循环内调用的方法跳出 for 循环

lisp - 对多个原子使用读取时条件化