Last active
August 29, 2015 14:02
-
-
Save hachibeeDI/5be7b3a96d261b608b24 to your computer and use it in GitHub Desktop.
Haskellの合成演算子 . を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
def _compose(f_t_u, f_u_r): | |
return lambda t: f_u_r(f_t_u(t)) | |
class Compose(object): | |
def __init__(self): | |
# :type: T -> U | |
self.func = lambda a: a | |
def __call__(self, val): | |
return self.func(val) | |
def composable(original_func): | |
''' | |
decorator to dispatch the function should be chaining method of masala.Stream | |
:type original_func: U -> V | |
''' | |
func_name = original_func.__name__ | |
def _compose_with_method_chaining(self): | |
self.func = _compose(self.func, original_func) | |
return self | |
setattr(Compose, func_name, _compose_with_method_chaining) | |
return original_func | |
@composable | |
def to_i(x): | |
return int(x) | |
@composable | |
def to_s(i): | |
return str(i) | |
@composable | |
def add_2(i): | |
return i + 2 | |
@composable | |
def decoration(s): | |
return '<< ' + s + '!!! >>' | |
if __name__ == '__main__': | |
composer = Compose() | |
print composer . to_i() . add_2() . add_2()(111) | |
print Compose() . to_i() . add_2() . add_2() . to_s() (22222) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment