I generalized clojure's loop
/recur
trampoline so that it works with indirect recursion:
const trampoline = f => (...args) => {
let acc = f(...args);
while (acc && acc.type === recur) {
let [f, ...args_] = acc.args;
acc = f(...args_);
}
return acc;
};
const recur = (...args) =>
({type: recur, args});
const even = n =>
n === 0
? true
: recur(odd, n - 1);
const odd = n =>
n === 0
? false
: recur(even, n - 1);
console.log(
trampoline(even) (1e5 + 1)); // false
However, I have to call the trampoline explicitly on the call side. Is there a way to make it implicit again, as with loop
/recur
?
Btw., here is loop
/recur
:
const loop = f => {
let acc = f();
while (acc && acc.type === recur)
acc = f(...acc.args);
return acc;
};
const recur = (...args) =>
({type: recur, args});