英文:
Tail Call Optimization in Go
问题
Go编程语言现在是否优化尾调用?如果不是,它是否至少优化函数对自身的尾递归调用?
英文:
Does the Go programming language, as of now, optimize tail calls? If not, does it at least optimize tail-recursive calls of a function to itself?
答案1
得分: 19
你可以在互联网上找到的一切,即“Go在某些情况下支持尾递归”,并且在邮件列表中有所提及:
> 在某些情况下,6g/8g已经支持了,而gccgo在某种程度上更加通用。
>
> 我们目前没有计划改变语言,要求编译器在所有情况下都实现尾调用优化。如果你必须使用尾调用,可以使用循环或goto语句。
要了解这些情况,最好深入研究golang源代码,它是开放的。
英文:
Everything you can find over the Internet, that "Go supports tailable recursions in some cases", and that was told in mailing list:
> It is already there in 6g/8g for certain cases, and in gccgo somewhat
> more generally.
>
> We do not currently plan to change the language to require that
> compilers implement tail call optimization in all cases. If you must
> have a tail call, you use a loop or a goto statement.
To get those cases you'd better dig into golang source, which is open.
答案2
得分: 5
我刚刚写了一个新的库来处理这个限制。感谢Go 1.18带来的新的泛型语言特性。
现在,类型安全的无栈互递归函数成为可能。
https://github.com/kandu/go_tailcall
英文:
I just wrote a new library to deal with this restriction. Thanks to the new generics language feature comes with Go 1.18.
Now, type safe stackless mutually recursive functions are possible.
答案3
得分: 4
扩展@Rostyslav的优秀答案。如果你必须要有一个尾调用(在这个例子中是一个尾递归调用),你可以像这样做。
package main
import "fmt"
func tail(i int) {
if i == 0 {
return
} else {
fmt.Println(i)
tail(i - 1) //尾递归调用
}
}
func main() {
tail(3) //3, 2, 1
}
英文:
Extending @Rostyslav's excellent answer. If you must have a tail call, (in this example a tail recursive call) you can do something like this.
package main
import "fmt"
func tail(i int) {
if i == 0 {
return
} else {
fmt.Println(i)
tail(i - 1) //tail recursive call
}
}
func main() {
tail(3) //3, 2, 1
}
答案4
得分: 3
它不会。根据核心开发团队在邮件列表上的说法,也没有任何计划。
英文:
It does not. Nor is there any plan to according to the core development team on the mailing list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论