Hacker News new | ask | show | jobs
by PhineasRex 3582 days ago
It looks like tail call optimization only works in simple situations.

    let rec foo i = if i < 0 then "foo" else bar (i - 1)
    and bar i = if i < 0 then "bar" else foo (i - 1)

    function foo(i) {
      if (i < 0) {
        return "foo";
      }
      else {
        return bar(i - 1 | 0);
      }
    }
    
    function bar(i) {
      if (i < 0) {
        return "bar";
      }
      else {
        return foo(i - 1 | 0);
      }
    }
It would be nice to get a warning when tail calls cannot be optimized.
1 comments

yes, we will have this warning when upgraded into OCaml 4.04 Note that optimizing mutual recursive call is a very hard problem it needs VM level support
Mutual tail call optimization requires VM level support in general but can be accomplished within a compiliation unit (module) via inlining.
Seems like it should also be possible to have the compiler employ JavaScript generator functions (i.e. `yield`) and iteration as a substitute for growing the stack, which might be a bit more flexible than rewriting in terms of loops+thunks, though the concept is the same.