Skip to content

Instantly share code, notes, and snippets.

@stangirala
Last active September 19, 2016 02:34
Show Gist options
  • Save stangirala/c3b1431395560e9b85a457f89c67ee61 to your computer and use it in GitHub Desktop.
Save stangirala/c3b1431395560e9b85a457f89c67ee61 to your computer and use it in GitHub Desktop.
A monoid in python
from collections import defaultdict
class Monoid():
def __init__(self, zero, foldOp, liftFunctor=None):
self.store = defaultdict(zero)
self.liftFunctor = liftFunctor
self.foldOp = foldOp
self.zero = zero
def fold(self, key, vals):
''' reduce is a subset of fold :) '''
_key = self.liftFunctor(key)
self.store[_key] = reduce(self.foldOp, [reduce(self.foldOp, vals), self.store[_key]])
def __call__(self, args):
self.fold("default", args)
def __str__(self):
return str(self.store)
if __name__ == '__main__':
sumAggregator = Monoid(lambda : 0, lambda val1, val2: val1+val2, lambda key: key)
sumAggregator([1, 2, 3, 4, 5])
print sumAggregator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment