Created
December 17, 2018 18:28
-
-
Save betafcc/6ec29b4aa14f069e8046048a785c133f to your computer and use it in GitHub Desktop.
Dead simple infix function application support in python, with sections partial application also
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
class infix: | |
""" | |
Makes a function 'infix' eg: | |
>>> @infix | |
... def power(x, n): | |
... return x ** n | |
>>> 2 |power| 3 | |
8 | |
Can be partially aplied: | |
>>> cube = power|3 | |
>>> cube(2) | |
8 | |
>>> base2 = 2|power | |
>>> base2(3) | |
8 | |
Useful with higher-order functions: | |
>>> list(map(power|3, [1, 2, 3, 4, 5])) | |
[1, 8, 27, 64, 125] | |
""" | |
def __init__(self, function): | |
self._function = function | |
def __call__(self, *args, **kwargs): | |
return self._function(*args, **kwargs) | |
def __ror__(self, left_argument): | |
return left_section(self._function, left_argument) | |
def __or__(self, right_argument): | |
return right_section(self._function, right_argument) | |
class left_section: | |
def __init__(self, function, left_argument): | |
self._function = function | |
self._left_argument = left_argument | |
def __call__(self, *args, **kwargs): | |
return self._function(self._left_argument, *args, **kwargs) | |
__or__ = __call__ | |
class right_section: | |
def __init__(self, function, right_argument): | |
self._function = function | |
self._right_argument = right_argument | |
def __call__(self, arg, *args, **kwargs): | |
return self._function(arg, self._right_argument, *args, **kwargs) | |
__ror__ = __call__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why
|func|
instead of<func>
? Tried it, python has branch exclusion rules that makes it impossible when using<
and>
at the same time. Partially applying sections works thou