简体   繁体   English

Rebol尾调用优化

[英]Rebol Tail Call Optimization

I come from a functional programming background and think first about recursive solutions to problems rather than iterative ones. 我来自函数式编程背景,首先考虑问题的递归解决方案而不是迭代解决方案。 I'm starting to work with Rebol a bit (specifically R3) and have written a solution to the primefactor kata using a tail-recursive function with an accumulator. 我开始使用Rebol(特别是R3),并使用带累加器的尾递归函数为primefactor kata编写了一个解决方案。 But with any sufficiently large input I blow the stack. 但是如果有足够大的输入,我会把堆叠吹掉。 I have a script for Rebol2 called "tail-func.r" which implements a version of tail-call optimization that AFAIK has not been ported to R3. 我有一个名为“tail-func.r”的Rebol2脚本,它实现了AFAIK尚未移植到R3的尾调用优化版本。 I know that Rebol 3 implements things differently than R2 in many cases, so is there a way to get TCO in Rebol 3 without any extra code? 我知道在很多情况下Rebol 3的实现方式与R2不同,所以有没有办法在Rebol 3中获得TCO而不需要任何额外的代码? If not, is there a simpler way to get it without porting the old script? 如果没有,有没有更简单的方法来获得它而不移植旧脚本?

Edited to add my code: 编辑添加我的代码:

primefactors: function [n m factors] [
  either n > 1
    [ either (modulo n m) == 0
      [ primefactors (n / m) m (append factors m) ]
      [ primefactors n (m + 1) factors ] ]
    [ factors ]
  ]

  primefactors 30 2 (copy []) => [2 3 5]

Not without code, sorry. 不是没有代码,抱歉。 Rebol isn't compiled, so there's no way to know ahead of time exactly what constitutes a tail call. Rebol没有编译,所以没有办法提前知道尾部调用的确切构成。 Even calls to the return function propagate back up the call stack, quickly but not by a goto. 甚至对return函数的调用也会快速传回调用堆栈,但不会通过goto传播。

IIRC the author of tail-func works on Rebol 3 now, and whether or not he does it should be easy to port over. IIRC的尾部功能的作者现在在Rebol 3上工作,无论他是否这样做都应该很容易移植。 Now that you mention it I'll take a look. 现在你提到它我会看看。 Function generators and preprocessors are easy to do in Rebol. 函数生成器和预处理器在Rebol中很容易实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM