Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Say we have an array (in JavaScript term) or list (in Python term), this article illustrate a simple functional programming example. i.e.
- ```
- Input: [1, 2, 3, 4, 5]
- Process: square each element
- Output: [1, 4, 9, 16, 25]
- ```
- # JavaScript Solution
- In JavaScript we use `map()` to do functional programming. e.g.
- ```.js
- // define a function suitable for JavaScript functional programming
- const square_it = (element) => element ** 2
- // create a dummy array
- const a = [1, 2, 3, 4, 5]
- // apply square to each element of the array
- const a2 = a.map(square_it)
- // print result to terminal
- console.log(a2) // [ 1, 4, 9, 16, 25 ]
- ```
- # Python Solution
- In Python, we can do something similar with list comprehension like this:
- ```.py
- # define a function suitable for Python functional programming
- def square_it(element):
- return element ** 2
- # create a dummy list
- a = [1, 2, 3, 4, 5]
- # apply square to each element of the list
- a2 = [square_it(x) for x in a]
- # print result to terminal
- print(a2) # [0, 1, 4, 9, 16]
- ```
- See the similarity?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement