Last active
August 19, 2016 13:48
-
-
Save mebusw/7548327ffdc261599aa7 to your computer and use it in GitHub Desktop.
This file contains 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): | |
def __init__(self, func): | |
self.func = func | |
def __ror__(self, other): | |
def generator(): | |
for obj in other: | |
if obj is not None: | |
yield self.func(obj) | |
return generator() | |
@Pipe | |
def even_filter(num): | |
return num if num % 2 == 0 else None | |
@Pipe | |
def multiply_by_three(num): | |
return num*3 | |
@Pipe | |
def convert_to_string(num): | |
return 'The Number: %s' % num | |
@Pipe | |
def echo(item): | |
print item | |
return item | |
def force(sqs): | |
print sqs | |
for item in sqs: print item | |
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
force(nums | even_filter | multiply_by_three | convert_to_string | echo) | |
from pipe import * | |
def i(k): | |
guess=1 | |
yield guess | |
while abs(guess*guess-k)<.001: | |
guess=(guess+k/guess)/2. | |
yield guess | |
return | |
for z in i(4): | |
print z, | |
def improve(guess, x): | |
return (guess+x/guess)/2. | |
K = 2 | |
print reduce(lambda guess, _: improve(guess, K), range(4), 1) | |
# reduce(lambda guess, _: improve(guess, K), range(10), 1) | take_while(lambda guess: abs(guess*guess-K)<.001) | |
# linear recursive | |
def lsum(f, a, b): | |
if (a>b): | |
return 0 | |
else: | |
return f(a)+ lsum(f, a+1, b) | |
print lsum(lambda x:x, 1, 5) | |
# tail recursive | |
def tsum(f, a, b): | |
def loop(a, acc): | |
if a>b: | |
return acc | |
else: | |
return loop(a+1, acc + f(a)) | |
return loop(a,0) | |
print tsum(lambda x:x, 1, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment