Last active
January 5, 2019 05:25
-
-
Save shiracamus/e7d5bd628db8b3ac7dd385db702149b6 to your computer and use it in GitHub Desktop.
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 Pipe: | |
def __init__(self, func, *args, **kwargs): | |
self.func, self.args, self.kwargs = func, args, kwargs | |
def __call__(self, *args, **kwargs): | |
return Pipe(self.func, *self.args, *args, **self.kwargs, **kwargs) | |
def __or__(self, pipe): | |
if not isinstance(pipe, Pipe): | |
raise TypeError("unsupported operand type(s) for |" | |
f": '{type(self).__name__}' and '{type(pipe).__name__}'") | |
return Pipe(lambda value: value | self | pipe) | |
def __ror__(self, value): | |
return self.func(*self.args, value, **self.kwargs) | |
join = Pipe(lambda joiner, items: joiner.join(items)) | |
cap = Pipe(lambda text: text.capitalize()) | |
surround = Pipe(lambda decoration, text: f"{decoration} {text} {decoration}") | |
collect = Pipe(lambda pipe, items: [item | pipe for item in items]) | |
out = Pipe(lambda *args, **kwargs: print(*args, **kwargs)) | |
['ruby', '2.6'] | join('-') | cap | surround('|') | out | |
batch = join('-') | cap | surround('|') | |
['python', '3.7.1'] | batch | out | |
[['ruby', '2.6'], ['python', '3.7.1']] | collect(batch) | out | |
("hello", "world") | join(", ") | cap | out("log:", end="!\n") |
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
| Ruby-2.6 | | |
| Python-3.7.1 | | |
['| Ruby-2.6 |', '| Python-3.7.1 |'] | |
log: Hello, world! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment