Created
October 24, 2017 03:59
-
-
Save bromne/00d10e07b1d75ae986cdf0990c9e64b4 to your computer and use it in GitHub Desktop.
末尾呼び出し最適化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 参考 | |
// 『Java による関数型プログラミング』7章 | |
let TailRec = { | |
done: function(result) { | |
return { | |
complete: true, | |
result: result | |
}; | |
}, | |
call: function(next) { | |
return { | |
complete: false, | |
next: next | |
} | |
}, | |
calculate: function(recursive) { | |
var iterator = recursive; | |
while (true) { | |
if (iterator.complete) | |
return iterator.result; | |
else | |
iterator = iterator.next(); | |
} | |
} | |
}; | |
let factorial = function(n) { | |
let fact = function(x, n) { | |
if (n == 1) | |
return TailRec.done(x); | |
else | |
return TailRec.call(() => fact(x * n, n - 1)); | |
}; | |
return TailRec.calculate(fact(1, n)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment