Created
June 16, 2018 02:24
-
-
Save rnagasam/d16411a90131ed5de614657ef9e64701 to your computer and use it in GitHub Desktop.
Infix functions in Python
This file contains hidden or 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
| from functools import partial | |
| class Infix(object): | |
| def __init__(self, func): | |
| self.func = func | |
| def __or__(self, other): | |
| return self.func(other) | |
| def __ror__(self, other): | |
| return Infix(partial(self.func, other)) | |
| def __call__(self, v1, v2): | |
| return self.func(v1, v2) | |
| @Infix | |
| def o(f,g): | |
| return lambda x: f(g(x)) | |
| # Example of use (composition with |o|) | |
| # | |
| # >> f = lambda x: x*3 | |
| # >> g = lambda x: x-15 | |
| # >> h = f |o| g |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment