nupanick

functional javascript

Oct 5th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html><body><pre><script>
  2.  
  3. document.writeln('Hello, world!');
  4.  
  5. // functional programming test
  6. let factorial = function (x) {
  7.   let fact_iter = function fact_iter (x, acc) {
  8.     if (x === 0) {
  9.       return acc }
  10.     else {
  11.       return fact_iter (x-1, acc*x) }}
  12.   return fact_iter (x, 1) }
  13.  
  14. document.writeln("5! = " + factorial(5));
  15. document.writeln("10! = " + factorial(10));
  16.  
  17. // no tail optimization, so: trampoline version.
  18. let safer_factorial = function (x) {
  19.  
  20.   // build the trampoline
  21.  
  22.   let trampoline_factorial = function trampoline_factorial(x, acc) {
  23.     if (x === 0) {
  24.       return {next: null, result: acc}}
  25.     else {
  26.       return {next: function () {return trampoline_factorial(x-1, x*acc)}}}}
  27.  
  28.   // wheee!!!
  29.  
  30.   var state = trampoline_factorial(x, 1);
  31.  
  32.   while (state.next) {
  33.     state = state.next()}
  34.  
  35.   return state.result }
  36.  
  37. document.writeln("7! = " + safer_factorial(7));
  38.  
  39. </script></pre></body></html>
Add Comment
Please, Sign In to add comment