Created
October 15, 2015 06:34
-
-
Save tkhoa2711/2eed483baa057486f61b to your computer and use it in GitHub Desktop.
Functional 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
import time | |
def tail(f, from_start=False): | |
try: | |
if from_start: | |
f.seek(0, 2) # go to the end of file | |
while True: | |
line = f.readline() | |
if not line: | |
time.sleep(0.1) | |
continue | |
yield line | |
except KeyboardInterrupt: | |
pass | |
except Exception as ex: | |
raise ex | |
def uniq(iterable, key=lambda x: x): | |
previous = set() | |
for v, k in ((elem, key(elem)) for elem in iterable): | |
if k not in previous: | |
yield v | |
previous.add(k) | |
def ireduce(func, iterable, initializer=None): | |
it = iter(iterable) | |
value = next(it) if initializer is None else initializer | |
for element in it: | |
value = func(value, element) | |
yield value | |
def _fold(func, iterable, iterize): | |
it = iterize(iterable) | |
value = next(it) | |
yield value | |
for i in it: | |
value = func(value, i) | |
yield value | |
def foldl(func, iterable): | |
for i in _fold(func, iterable, iter): | |
yield i | |
def foldr(func, iterable): | |
for i in _fold(func, iterable, reversed): | |
yield i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment