SICP递归过程与迭代过程:使用递归过程生成迭代过程

编程入门 行业动态 更新时间:2024-10-25 02:27:20
本文介绍了SICP递归过程与迭代过程:使用递归过程生成迭代过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在SICP 第1.2节。 1 作者在下面给出了一个代码示例,说明如何使用迭代过程来解决阶乘问题:

in SICP Section 1.2.1 The author giving such a code example below to show how to using iterative process to solve the factorial problem:

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

并说我们将一个递归过程称为事实 - 因为生成一个迭代过程,这似乎令人不安。但是,过程确实是迭代的:它的状态完全被它的三个状态变量捕获,并且解释器需要只跟踪三个变量才能执行该过程。

我不明白作者的意思。递归过程和递归过程之间有什么区别?为什么他说下面的递归过程会产生迭代过程?

I don't understand what the author mean. What's the difference between a recursive procedure and a recursive process? And why did he say the recursive procedure below generating an iterative process?

推荐答案

递归过程需要在递归时保持调用者的状态通话正在进行中。例如,如果您写道:

A recursive process needs to maintain the state of the caller while the recursive call is in progress. For instance, if you wrote:

(define (fact-recurse n) (if (< n 2) 1 (* n (fact-recurse (- n 1)))))

外部调用必须记住 n 并等待内部调用返回才能执行乘法运算。如果你调用(fact-recurse 10),当函数到达递归结束时,将有9个堆叠乘法挂起。

the outer call has to remember n and wait for the inner call to return before it can perform the multiplication. If you call (fact-recurse 10) there will be 9 stacked multiplications pending when the function reaches the end of its recursion.

但是在迭代过程中,可以丢弃先前的状态。这在示例代码中是可能的,因为所需的所有信息都作为递归调用中的参数传递。外部调用中的变量不再需要,因此不需要在堆栈上保留任何内容。

But in an iterative process, the earlier state can be discarded. This is possible in the example code because all the information needed is passed as parameters in the recursive call. The variables in the outer call are no longer needed, so nothing needs to be kept on a stack.

由于不再需要外部调用的参数,递归调用可以被翻译成作业:

Since the outer call's parameters are no longer needed, the recursive call can be translated into assignments:

(set! product (* counter product)) (set! counter (+ counter 1) (set! max-count max-count)

然后它只是跳跃到程序的开头。

and then it just jumps to the beginning of the procedure.

更多推荐

SICP递归过程与迭代过程:使用递归过程生成迭代过程

本文发布于:2023-11-30 21:10:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   过程   迭代   SICP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!