Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html><body><pre><script>
- document.writeln('Hello, world!');
- // functional programming test
- let factorial = function (x) {
- let fact_iter = function fact_iter (x, acc) {
- if (x === 0) {
- return acc }
- else {
- return fact_iter (x-1, acc*x) }}
- return fact_iter (x, 1) }
- document.writeln("5! = " + factorial(5));
- document.writeln("10! = " + factorial(10));
- // no tail optimization, so: trampoline version.
- let safer_factorial = function (x) {
- // build the trampoline
- let trampoline_factorial = function trampoline_factorial(x, acc) {
- if (x === 0) {
- return {next: null, result: acc}}
- else {
- return {next: function () {return trampoline_factorial(x-1, x*acc)}}}}
- // wheee!!!
- var state = trampoline_factorial(x, 1);
- while (state.next) {
- state = state.next()}
- return state.result }
- document.writeln("7! = " + safer_factorial(7));
- </script></pre></body></html>
Add Comment
Please, Sign In to add comment