Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. Say we have an array (in JavaScript term) or list (in Python term), this article illustrate a simple functional programming example. i.e.
  2.  
  3. ```
  4. Input: [1, 2, 3, 4, 5]
  5. Process: square each element
  6. Output: [1, 4, 9, 16, 25]
  7. ```
  8.  
  9. # JavaScript Solution
  10.  
  11. In JavaScript we use `map()` to do functional programming. e.g.
  12.  
  13. ```.js
  14. // define a function suitable for JavaScript functional programming
  15. const square_it = (element) => element ** 2
  16.  
  17. // create a dummy array
  18. const a = [1, 2, 3, 4, 5]
  19.  
  20. // apply square to each element of the array
  21. const a2 = a.map(square_it)
  22.  
  23. // print result to terminal
  24. console.log(a2) // [ 1, 4, 9, 16, 25 ]
  25. ```
  26.  
  27. # Python Solution
  28.  
  29. In Python, we can do something similar with list comprehension like this:
  30.  
  31. ```.py
  32. # define a function suitable for Python functional programming
  33. def square_it(element):
  34. return element ** 2
  35.  
  36. # create a dummy list
  37. a = [1, 2, 3, 4, 5]
  38.  
  39. # apply square to each element of the list
  40. a2 = [square_it(x) for x in a]
  41.  
  42. # print result to terminal
  43. print(a2) # [0, 1, 4, 9, 16]
  44. ```
  45.  
  46. See the similarity?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement