Skip to content

Instantly share code, notes, and snippets.

@Gerenuk
Last active December 21, 2017 22:34
Show Gist options
  • Save Gerenuk/327746121156437941f478b3724c03d7 to your computer and use it in GitHub Desktop.
Save Gerenuk/327746121156437941f478b3724c03d7 to your computer and use it in GitHub Desktop.
Interpretation of a Monoid in Python
from functools import reduce
from operator import add
def monoid(combine, create=lambda x:x):
def wrapped(val):
return Monoid(combine, create(val))
return wrapped
class EmptyMonoid:
def __add__(self, other):
return other
class Monoid:
empty_monoid=EmptyMonoid() # singleton
def __init__(self, combine, val):
self.combine=combine
self.val=val
def __add__(self, other):
if other is self.empty_monoid:
return self
return Monoid(self.combine, self.combine(self.val, other.val))
def __repr__(self):
return f"m:{self.val}" # Python 3.6
def fold_tree(mono, tree):
if not isinstance(tree, list): # we got down to a leaf
return mono(tree)
return reduce(add, [fold_tree(mono, tree_part) for tree_part in tree], Monoid.empty_monoid)
tree=[[[1,2],[3,4]],[[5,6],[7,8],[9]]] # trees are built and detected as lists
fold_tree(monoid(add), tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment