Created
July 6, 2019 15:38
-
-
Save nikoheikkila/53727d4e06354d5d59bb9c5fbe604bf7 to your computer and use it in GitHub Desktop.
Playing with pipeable lists in Python 3
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 __future__ import annotations | |
| from typing import Any, Callable, Union, Tuple | |
| from functools import reduce | |
| class Pipe(list): | |
| """Type declarations""" | |
| Predicate = Callable[[Any], bool] | |
| Mappable = Callable[[Any], Any] | |
| def head(self) -> Any: return self[0] | |
| def last(self) -> Any: return self[-1] | |
| def tail(self) -> Pipe: return Pipe(self[1:]) | |
| def init(self) -> Pipe: return Pipe(self[:-1]) | |
| def length(self) -> int: return len(self) | |
| def null(self) -> bool: return self.length() == 0 | |
| def map(self, fn: Mappable) -> Pipe: return Pipe([fn(i) for i in self]) | |
| def filter(self, fn: Predicate) -> Pipe: return Pipe([i for i in self if fn(i)]) | |
| def reverse(self) -> Pipe: return Pipe(self[::-1]) | |
| def sum(self) -> float: return reduce(lambda a, b: float(a) + float(b), self, 0) | |
| def product(self) -> float: return reduce(lambda a, b: float(a) * float(b), self, 1) | |
| def each(self, fn: Mappable) -> Pipe: | |
| self.map(fn) | |
| return self | |
| def all(self, fn: Predicate) -> bool: | |
| for i in self: | |
| if not fn(i): return False | |
| return True | |
| def any(self, fn: Predicate) -> bool: | |
| for i in self: | |
| if fn(i): return True | |
| return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment