Instantly share code, notes, and snippets.

Atlas7/fun_js_vs_py.md Last active Apr 27, 2017

Function Programming Example - square elements in an array (JavaScript) or list (Python)

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.

```// 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:

```#  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?

to join this conversation on GitHub. Already have an account? Sign in to comment