まず、私はその後、私は
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 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
を書き込むことによって開始します
今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スタイルのループ/ recur trampolineを使用する - 補助ヘルパーが必要なので、このスタイルを好む(つまり、上記の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))
"トランポリン機能" とは? –
何か試しましたか? – Bergi