Tail recursive functions allow for a wider range of optimisations than general recursive functions. For this reason, much research has gone into the transformation and optimisation of this family of functions, in particular those written in continuation passing style (CPS). Though the CPS transformation, capable of transforming any recursive function to an equivalent tail recursive one, is deeply problematic in the context of reversible programming (as it relies on troublesome features such as higher-order functions), we argue that relaxing (local) reversibility to (global) invertibility drastically improves the situation. On this basis, we present an algorithm for tail recursion conversion specifically for invertible functions. The key insight is that functions introduced by program transformations that preserve invertibility, need only be invertible in the context in which the functions subject of transformation calls them. We show how a bespoke data type, corresponding to such a context, can be used to transform invertible recursive functions into a pair of tail recursive function acting on this context, in a way where calls are highlighted, and from which a tail recursive inverse can be straightforwardly extracted.
翻译:尾递归函数比一般递归函数能够实现更广泛的优化。为此,大量研究致力于这类函数的变换与优化,特别是以续延传递风格(CPS)编写的函数。尽管CPS变换能够将任意递归函数转化为等价的尾递归函数,但在可逆编程语境中存在深层问题(因其依赖于高阶函数等棘手特性)。我们论证,将(局部)可逆性放宽至(全局)可逆性可大幅改善这一状况。基于此,我们提出一种专门针对可逆函数的尾递归转换算法。其关键洞见在于:通过保持可逆性的程序变换引入的函数,仅需在调用被变换函数的目标函数所处的上下文中可逆。我们展示一种定制数据类型(对应于该上下文),可如何用于将可逆递归函数变换为一对作用于该上下文的尾递归函数——在此变换中,函数调用得以显式标注,并可直接提取出尾递归形式的逆函数。