How to use OCaml's [@tailcall] annotation to assert tail-recursiveness?

落爺英雄遲暮 提交于 2019-12-12 09:54:12

问题


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?

Obvious, easy example:

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? *)

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)


回答1:


The docs say in subsection 18.1 that

“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.

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




回答2:


did you try :

let rec f = function
| 0 -> 0
| x -> (|>) (x - 1) (f[@tailcall])


来源:https://stackoverflow.com/questions/38843684/how-to-use-ocamls-tailcall-annotation-to-assert-tail-recursiveness

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!