Skip to content

Instantly share code, notes, and snippets.

@snk4tr
Last active July 31, 2018 07:47
Show Gist options
  • Save snk4tr/ea62f4f01fd789cc2e6eba4fc3da12d9 to your computer and use it in GitHub Desktop.
Save snk4tr/ea62f4f01fd789cc2e6eba4fc3da12d9 to your computer and use it in GitHub Desktop.
This gist shows the way to reduce python code size and complexity with some elements of functional programming.
class FunctionalWrapper(object):
def __init__(self, data):
self.data = data
def map(self, function):
"""Call `map` on the items in `data` using the provided `function`"""
return FunctionalWrapper(list(map(function, self.data)))
def reduce(self, function):
"""Call `reduce` on the items in `data` using the provided `function`"""
return list(reduce(function, self.data))
def filter(self, function):
"""Call `filter` on the items in `data` using the provided `function`"""
return FunctionalWrapper(list(filter(function, self.data)))
def __eq__(self, other):
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
def __getattr__(self, name): return getattr(self.data, name)
def __getitem__(self, k): return self.data.__getitem__(k)
def __repr__(self): return 'FunctionalWrapper({0})'.format(repr(self.data))
def __str__(self): return 'FunctionalWrapper({0})'.format(str(self.data))
from functional_wrapper import FunctionalWrapper
# Create some data
mapData = FunctionalWrapper(range(5))
# Define a function to be applied to each element
f = lambda x: x + 3
# Imperative programming: loop through and create a new object by applying f
mapResult = FunctionalWrapper([]) # Initialize the result
for element in mapData:
mapResult.append(f(element)) # Apply f and save the new value
print('Result from for loop: {0}'.format(mapResult))
# >>> Result from for loop: FunctionalWrapper([3, 4, 5, 6, 7])
# Functional programming: use map rather than a for loop
print('Result from map call: {0}'.format(mapData.map(f)))
# >>> Result from map call: FunctionalWrapper([3, 4, 5, 6, 7])
# Note that the results are the same but that the map function abstracts away the implementation
# and requires less code
from functional_wrapper import FunctionalWrapper
# Example of a mult-line expression statement
# Note that placing parentheses around the expression allow it to exist on multiple lines without
# causing a syntax error.
dataset = FunctionalWrapper(range(10))
dataset = (dataset
.map(lambda x: x + 2)
.reduce(lambda x, y: x * y))
finalSum = dataset.map(lambda x:x*5).filter(lambda x: x%2==0).reduce(lambda x,y:x+y)
print(finalSum)
# >>> 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment