Skip to content

Instantly share code, notes, and snippets.

@rmariano
Created January 5, 2017 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmariano/4241f142cc0ae38cfd2a5e34415deb9a to your computer and use it in GitHub Desktop.
Save rmariano/4241f142cc0ae38cfd2a5e34415deb9a to your computer and use it in GitHub Desktop.
Functional programming wrapped in object
"""
Object that allows chaining functional programming operations
over a provided data set.
"""
from operator import add
from functools import partialmethod, reduce
class ChainedFunctional:
def __init__(self, data):
self.data = tuple(data)
def __str__(self):
return str(self.data)
def _2_ary_functional(self, user_function, fx):
self.data = tuple(fx(user_function, self.data))
return self
def _1_ary_functional(self, fx):
return fx(list(self.data))
map = partialmethod(_2_ary_functional, fx=map)
filter = partialmethod(_2_ary_functional, fx=filter)
def reduce(self, user_function):
return reduce(user_function, self.data)
sum = partialmethod(_1_ary_functional, fx=sum)
__len__ = partialmethod(_1_ary_functional, fx=len)
data_pipeline = ChainedFunctional([1,2,3,4,5])
# [2, 4, 8, 16, 32]
# [16, 32]
result = data_pipeline.map(lambda x: 2 ** x) \
.filter(lambda x: x > 10)
print(result.reduce(add)) # 48
print(result.sum()) # 48
print(len(result)) # len([16, 32]) == 2
print(result) # (16, 32)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment