Created
January 13, 2020 22:01
-
-
Save vskrachkov/5d1b512c3354bd5444498a3fb90eb52e to your computer and use it in GitHub Desktop.
python, pipe, chain, monad, functor
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
from typing import Callable, Union | |
class Pipe: | |
def __init__(self, callable_: Callable): | |
self.callable_ = callable_ | |
def __rshift__(self, then: Union[Callable, "Pipe"]) -> "Pipe": | |
if not isinstance(then, Pipe): | |
then = Pipe(then) | |
then(self.result) | |
return then | |
def __call__(self, *args, **kwargs) -> "Pip": | |
self.result = self.callable_(*args, **kwargs) | |
return self | |
@Pipe | |
def put(v): | |
return v | |
def pipe(source, *chain: Callable): | |
for next_ in chain: | |
source = next_(source) | |
return source | |
def pipe_factory(source, *chain: Callable): | |
def evaluate(): | |
return pipe(source, *chain) | |
return evaluate | |
def main(): | |
put(3) >> (lambda x: (x ** 2, x * 10)) >> sum >> print | |
pipe(3, lambda x: (x ** 2, x * 10), sum, print) | |
new_pipe = pipe_factory(3, lambda x: (x ** 2, x * 10), sum, print) | |
new_pipe() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment