SHARE
TWEET

Untitled

a guest Jul 18th, 2019 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from __future__ import annotations
  2. from typing import Any, Callable, Union, Tuple
  3. from functools import reduce
  4.  
  5.  
  6. class Pipe(list):
  7.  
  8.     """Type declarations"""
  9.     Predicate = Callable[[Any], bool]
  10.     Mappable = Callable[[Any], Any]
  11.  
  12.     def head(self) -> Any: return self[0]
  13.     def last(self) -> Any: return self[-1]
  14.     def tail(self) -> Pipe: return Pipe(self[1:])
  15.     def init(self) -> Pipe: return Pipe(self[:-1])
  16.     def length(self) -> int: return len(self)
  17.     def null(self) -> bool: return self.length() == 0
  18.     def map(self, fn: Mappable) -> Pipe: return Pipe([fn(i) for i in self])
  19.     def filter(self, fn: Predicate) -> Pipe: return Pipe([i for i in self if fn(i)])
  20.     def reverse(self) -> Pipe: return Pipe(self[::-1])
  21.     def sum(self) -> float: return reduce(lambda a, b: float(a) + float(b), self, 0)
  22.     def product(self) -> float: return reduce(lambda a, b: float(a) * float(b), self, 1)
  23.  
  24.     def each(self, fn: Mappable) -> Pipe:
  25.         self.map(fn)
  26.         return self
  27.  
  28.     def all(self, fn: Predicate) -> bool:
  29.         for i in self:
  30.             if not fn(i): return False
  31.  
  32.         return True
  33.  
  34.     def any(self, fn: Predicate) -> bool:
  35.         for i in self:
  36.             if fn(i): return True
  37.  
  38.         return False
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top