Advertisement
amigojapan

high class functions in a nutshell

Apr 9th, 2014
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. This code is pseudo JavaScript
  2. function (x) {print x*x;}
  3. reduce(function(x,y) (return x+y), [1,2,3]) = 6
  4. add = function (x,y) return (x+y)
  5. x = [1,2,3][0]
  6.  
  7. Implementation of reduce
  8. for(i=1; i < [1,2,3].length; i++){
  9.     x = add(x,[1,2,3][i])
  10. }
  11. return x
  12.  
  13. reduce(add,[1,2,3]) = 6
  14.  
  15. how to use the same logic as nested for loops using map
  16. [[1,2],[3,4]]
  17. map(function (i) return map(function(ninja) j*2, i), [[1,2],[3,4]])
  18. less cryptic
  19. function double (i) {return 2*i}
  20. function doubleAll (i) {return map(double,i)}
  21. map(doubleAll,[[1,2],[3,4]])
  22.  
  23.  
  24. Here is some actual JavaScript that amigojapan wrote later to test the map and reduce functions
  25. <html>
  26. <head>
  27. <script type="text/javascript">
  28. print = function(x){alert(x);}
  29. sum = function(sum, current){
  30.     return (sum+current);
  31. }
  32. function show_prompt() {
  33.         var o="";
  34.         var list=[10,2,3];
  35.         list.map(print, list);
  36.         var total =list.reduce(sum);
  37.         o=total;
  38.         document.getElementById('output1').innerHTML=o;
  39. }
  40. window.onload = show_prompt;
  41. </script>
  42. </head>
  43. <div id="output1">No output</div>
  44. <body></body>
  45. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement