Skip to content

Instantly share code, notes, and snippets.

@pando85
Created August 17, 2017 09:23
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 pando85/c92327946ab11c36952db2c384bd698c to your computer and use it in GitHub Desktop.
Save pando85/c92327946ab11c36952db2c384bd698c to your computer and use it in GitHub Desktop.
compose functions in python like haskell
class Composable(object):
''' A function decorator that allows you to use Haskell style dot notation for function composition '''
fns = {}
def __init__(self, fn):
self.fn = fn
Composable.fns[fn.__name__] = fn
def __call__(self, *args, **kwargs):
''' simply calls the function '''
return self.fn(*args, **kwargs)
def __getattr__(self, other):
''' The returned function will only be able to be on the left of a composition, for now '''
return Composable(compose(self.fn, self.fns[other]))
# Examples:
@Composable
def add_17(x):
return x + 17
@Composable
def subtract_7(x):
return x - 17
add_17 . subtract_7 (10) == 20 # True
Composable(lambda x: x * 2) . add_17 . add_17 . subtract_7 == 54 # True
# Limitations
# - Anonymous functions can only be on the left hand side of a composition (because they don't have names)
# Ideas:
# - Get the module name and scope when creating a Composable
# - This will allow you to have a function with the same name from two different modules
# - It will also allow you to lookup unknown functions in the module it is being called from
@mcocdawc
Copy link

Cool ;)

@kamyar1979
Copy link

Where is 'compose' function then?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment