4 ms·
But can you do that with something like fibonacci? You can't just tail-call optimize that away, can you, since there are two recursive calls?
by AnimalMuppet 11y ago
But can you do that with something like fibonacci? You can't just tail-call optimize that away, can you, since there are two recursive calls?
- chriswarbo 11y agoI was under the impression that Schemes generally compile down to continuation-passing-style, and hence in the case of something like Fibonacci one of the recursive calls would be performed as a tail call, whilst the other would become part of the continuation, e.g. something like: function fib(n, k) { if (n == 0) k(1); if (n == 1) k(1); fib(n-1, function(f_1) { fib(n-2, function(f_2) { k(f_1 + f_2); }); }); }
- davexunit 11y agoThe natural recursive definition of a Fibonacci function is a different beast. The big issue with the naive and simple Fibonacci implementation is that it duplicates work, a ton of it. The 'map' above doesn't have this issue. To make Fibonacci efficient, it can be implemented as an iterative algorithm which isn't too bad to read. But there's better news! The recursive algorithm can be kept as-is, provided that the function is memoized, so that already computed values are cached.