问题
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