我概括了clojure的loop
/recur
蹦床,以便它与间接递归一起工作:
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
但是,我必须在调用方显式调用蹦床。有没有办法让它再次隐含,就像loop
/一样recur
?
顺便说一句,这里是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});