如何使用OCaml的[@tailcall]注释断言尾递归? [英] How to use OCaml's [@tailcall] annotation to assert tail-recursiveness?

查看:73
本文介绍了如何使用OCaml的[@tailcall]注释断言尾递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在OCaml中,使用[@tailcall]注释可以断言特定的函数调用是尾调用(因此希望您的整个函数是尾递归的).问题是:我应该在哪里准确放置注释?

In OCaml, the [@tailcall] annotation lets you assert that a particular function-call is a tail call (and so hopefully your whole function is tail recursive). The question is: Where do I place the annotation exactly?

显而易见的简单示例:

let rec f = function
  | 0 -> 0
  | x -> (f [@tailcall]) (x - 1) (* works like a charm *)

但是我看不到如何在不太明显"的地方做到这一点:

But I don't see how I can do it in "less obvious" places:

let rec f = function
  | 0 -> 0
  | x -> (|>) (x - 1) f (* uh? *)

我从汇编代码中看到,后一个示例被编译器识别为尾递归.因此,直到有人实现[@tailrec]为止:我应该将[@tailcall]批注确切地放置在哪里? (如果在第二个示例中完全有可能)

I can see from the assembly code that the latter example is recognized as tail recursive by the compiler. So until someone implements [@tailrec]: Where exactly do I place my [@tailcall] annotations? (if it's possible at all in the 2nd example)

推荐答案

文档说在第18.1小节

"ocaml.tailcall"或"tailcall"可以应用于函数应用程序,以检查该调用是否优化了尾调用.如果不是这种情况,则发出警告(51).

"ocaml.tailcall" or "tailcall" can be applied to function application in order to check that the call is tailcall optimized. If it it not the case, a warning (51) is emitted.

由于第二个示例不适用f,因此该属性在此上下文中不适用.

Since your second example does not apply f, the attribute is not applicable in this context.

这篇关于如何使用OCaml的[@tailcall]注释断言尾递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆