Skip to content

Instantly share code, notes, and snippets.

@kadams54
Last active October 3, 2023 19:01
Show Gist options
  • Save kadams54/b53cd828aafd5c0f3f77b5b84ac80416 to your computer and use it in GitHub Desktop.
Save kadams54/b53cd828aafd5c0f3f77b5b84ac80416 to your computer and use it in GitHub Desktop.
Example of chaining functions

All the programs below implement these steps:

  1. Generate a list of 1-8, not including 8: [1, 2, 3, 4, 5, 6, 7]
  2. Filter that list to even values: [2, 4, 6]
  3. Return each value N repeated N times: [2, 2, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
from pydash import py_
def is_even(n):
return n % 2 == 0
def repeat(n, times):
return [n] * times
def concat(list_a, list_b):
return [*list_a, *list_b]
def computed():
return (
py_(py_.range(1, 8))
.filter(is_even)
.map(lambda n: repeat(n, n))
.reduce(concat, [])
.value()
)
print(computed())
# > python compute-with-python.py
# [2, 2, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
from functools import reduce
def is_even(n):
return n % 2 == 0
def repeat(n, times):
return [n] * times
def concat(list_a, list_b):
return [*list_a, *list_b]
def computed():
numbers = range(1, 8)
evens = filter(is_even, numbers)
repeats = map(lambda n: repeat(n, n), evens)
values = reduce(concat, repeats, [])
return values
print(computed())
# > python compute.py
# [2, 2, 4, 4, 4, 4, 6, 6, 6, 6, 6, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment