gpt4 book ai didi

lisp - 哪个是尾递归?

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:26 24 4
gpt4 key购买 nike

我看到以下两个函数在语法上都是尾递归函数,但是,在racket中,它们中的哪一个真正被视为尾递归,或两者兼而有之?我的意思是它是否被解释器优化为尾递归

;;1
(define (foo i m s)
(if (< i m)
(foo (+ i 1) m (+ i s))
s))

;;2
(define (foo i m s)
(if (= i m)
s
(foo (+ i 1) m (+ i s))))

在其他 lisp 中是否有任何不同的答案?

最佳答案

两者都是尾递归的,因为递归调用是在尾位置完成的,也就是说:这是调用递归时最后完成的事情。在显示的过程中,if 表达式中的后续部分和替代部分的顺序是否颠倒并不重要。

并通过Scheme的specification ,所有尾递归都必须优化掉,无论它们出现在代码中的什么位置,从句法上讲:

Implementations of Scheme must be properly tail-recursive. Procedure calls that occur in certain syntactic contexts called tail contextsare tail calls. A Scheme implementation is properly tail-recursive if it supports an unbounded number of active tail calls. A call is active if the called procedure may still return. Note that this includes regular returns as well as returns through continuations captured earlier by call-with-current-continuation that are later invoked. In the absence of captured continuations, calls could return at most once and the active calls would be those that had not yet returned. A formal definition of proper tail recursion can be found in Clinger's paper [5]. The rules for identifying tail calls in constructs from the (rnrs base (6)) library are described in section 11.20.

关于lisp - 哪个是尾递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com