Last active
September 29, 2016 18:04
-
-
Save lyndsysimon/96977376ff5a743b737a3a30b607e6c8 to your computer and use it in GitHub Desktop.
Python functional composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class composable: | |
def __init__(self, func): | |
self.func = func | |
def __call__(self, *args, **kwargs): | |
return self.func(*args, **kwargs) | |
def __or__(self, other): | |
return lambda *args, **kwargs: self(other(*args, **kwargs)) | |
def __ror__(self, other): | |
return lambda *args, **kwargs: other(self(*args, **kwargs)) | |
@composable | |
def a(x): | |
return x + x | |
@composable | |
def b(x): | |
return '{0}{0}'.format(x) | |
@composable | |
def c(x): | |
return '-{}-'.format(x) | |
d = c | b | a | |
d(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment