arXivDaily arXiv每日学术速递 周一至周五更新
arXiv周末暂无论文更新,休息一下吧,周末愉快~~
arXiv 2102.09823cs.PL
收藏

尾模缺点

Tail Modulo Cons

Frédéric Bour, Basile Clément, Gabriel Scherer

摘要:

OCaml函数调用消耗系统堆栈上的空间。操作系统对堆栈空间设置了默认限制,这些限制远低于可用内存。如果一个程序用完了堆栈空间,就会出现可怕的“堆栈溢出”异常--程序崩溃。因此,OCaml程序员在编写递归函数时必须小心,保持在所谓的_tail-recursive_ fragment中,使用不消耗堆栈空间的_tail_ calls。这门学科对初学者和专家来说都是困难的来源。初学者必须学习递归,然后是尾递归。专家们对编写List.map的“正确”方法意见不一。直接版本很漂亮,但不是尾递归的,所以它会在较大的输入上崩溃。朴素的尾递归转换比直接转换(稍微)慢一些,专家们可能希望避免这种代价。一些库提出了可怕的实现,手工展开代码,以弥补这种性能损失。一般来说,尾递归需要程序员手动执行复杂的程序转换。在这项工作中,我们提出了一个实现的“尾模Cons”(TMC)的OCaml。TMC是一个针对非尾递归函数片段的程序转换,它以_destination-passing style_重写它们。支持的片段比其他方法(如延续传递风格)要小,但转换后的代码的性能与直接的非尾递归版本相当。TMC片段中有许多有用的函数,可以遍历递归数据结构并重建另一个递归结构,特别是`List.map`(以及`List.filter`、`List.append`等)。最后,这些函数可以以一种漂亮的方式编写,在所有输入上都是正确的,并且高效。

英文摘要:

OCaml function calls consume space on the system stack. Operating systems set default limits on the stack space which are much lower than the available memory. If a program runs out of stack space, they get the dreaded "Stack Overflow" exception -- they crash. As a result, OCaml programmers have to be careful, when they write recursive functions, to remain in the so-called _tail-recursive_ fragment, using _tail_ calls that do not consume stack space. This discipline is a source of difficulties for both beginners and experts. Beginners have to be taught recursion, and then tail-recursion. Experts disagree on the "right" way to write `List.map`. The direct version is beautiful but not tail-recursive, so it crashes on larger inputs. The naive tail-recursive transformation is (slightly) slower than the direct version, and experts may want to avoid that cost. Some libraries propose horrible implementations, unrolling code by hand, to compensate for this performance loss. In general, tail-recursion requires the programmer to manually perform sophisticated program transformations. In this work we propose an implementation of "Tail Modulo Cons" (TMC) for OCaml. TMC is a program transformation for a fragment of non-tail-recursive functions, that rewrites them in _destination-passing style_. The supported fragment is smaller than other approaches such as continuation-passing-style, but the performance of the transformed code is on par with the direct, non-tail-recursive version. Many useful functions that traverse a recursive datastructure and rebuild another recursive structure are in the TMC fragment, in particular `List.map` (and `List.filter`, `List.append`, etc.). Finally those functions can be written in a way that is beautiful, correct on all inputs, and efficient.

机构、总结、中文摘要均由AI分析而来,可能存在错误,请以论文正文为准。

↑