如何更改以下代码以使用trampoline功能?感谢。
var count = function (n) {
if(typeof n !== 'number' || n % 1 !== 0) return null;
if(n < 3) { return 1; }
console.log(n)
return count(n - 1) + count(n - 3)
}
答案 0 :(得分:0)
首先,我首先将count
写成纯粹的表达式
const count = (n) =>
n < 3
? 1
: count (n - 1)
+ count (n - 3)
// demo
for (let n = 0; n < 10; n = n + 1)
console.log (n, count (n))
然后我将count
转换为继续传递样式
const count = (n, k = x => x) =>
n < 3
? k (1)
: count (n - 1, x =>
count (n - 3, y =>
k (x + y)))
// demo
for (let n = 0; n < 10; n = n + 1)
console.log (n, count (n))
既然count
处于尾部位置,我们可以很容易地将它放在蹦床上 - 你可以使用你想要的任何蹦床实现,当然
const countLoop = (n, k = x => x) =>
n < 3
? k (1)
: bounce (countLoop, n - 1, x =>
bounce (countLoop, n - 3, y =>
k (x + y)))
const count = (n) =>
trampoline (countLoop (n))
const trampoline = (acc) =>
{
while (acc && acc.tag === bounce)
acc = acc.f (...acc.values)
return acc
}
const bounce = (f, ...values) =>
({ tag: bounce, f, values })
// demo
for (let n = 0; n < 10; n = n + 1)
console.log (n, count (n))
或者我们可以使用clojure风格的循环/重复蹦床 - 我更喜欢这种风格,因为它需要一个辅助助手(即上面的countLoop
)
const count = (m) =>
loop ((n = m, k = x => x) =>
n < 3
? k (1)
: recur (n - 1, x =>
recur (n - 3, y =>
k (x + y))))
const loop = (f) =>
{
let acc = f ()
while (acc && acc.tag === recur)
acc = f (...acc.values)
return acc
}
const recur = (...values) =>
({ tag: recur, values })
// demo
for (let n = 0; n < 10; n = n + 1)
console.log (n, count (n))