Created
September 7, 2014 06:05
-
-
Save venuatu/0b35e331aeea9f3feb8f to your computer and use it in GitHub Desktop.
pipe.py: A simple functional list wrapper for 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
from pipe import * | |
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] | |
mod_primes = ~(pipe(primes) | |
| filter(lambda a: a > 20) | |
| map(lambda a: a * a) | |
| zip_index | |
) | |
summed_primes = ~(pipe(mod_primes) | |
| map(lambda a: a[1]) | |
| reduce(lambda a, b: a + b, 0) | |
) | |
print('primes: %s' % primes) | |
print('mutated primes: %s' % mod_primes) | |
print('sum: %s' % summed_primes) |
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(object): | |
"""pipe: a functional list wrapper""" | |
def __init__(self, list): | |
self.list = list | |
def __or__(self, filterer): | |
return pipe(filterer(self.list)) | |
def unwrap(self): | |
return self.list | |
def __invert__(self): | |
return self.list | |
def __repr__(self): | |
return 'pipe('+ repr(self.list) +')' | |
def filter(func): | |
def filterfn(list): | |
return [x for x in list if func(x)] | |
return filterfn | |
def map(func): | |
def mapfn(list): | |
return [func(x) for x in list] | |
return mapfn | |
def reduce(func, initial=None): | |
def reducefn(list, initial=initial): | |
for item in list: | |
initial = func(item, initial) | |
return initial | |
return reducefn | |
def zip(list): | |
def zipfn(orig): | |
return [(orig[i], list[i]) for i in xrange(min(len(list), len(orig)))] | |
return zipfn | |
def flip(list): | |
return [(j, i) for i, j in list] | |
def zip_index(list): | |
# return [x for x in enumerate(list)] | |
return ~(pipe(list) | zip(xrange(2**62)) | flip) |
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
primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] | |
mutated primes: [(0, 529), (1, 841), (2, 961), (3, 1369), (4, 1681), (5, 1849), (6, 2209)] | |
sum: 9439 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment