27 replies on 2 pages. Most recent reply: May 7, 2011 1:04 PM by Richard Silverman
def accept_block(func):
def wrap_generator(*args,**kwd):
gen = func(*args,**kwd)
def block_call(block=None):
if block:
res = gen.next()
try:
return block(res)
except TypeError:
return block(*res)
else:
return gen.next()
return block_call
return wrap_generator
@accept_block
def each(l):
for i in l:
yield i
# tribute to Ruby :)
import sys
puts = sys.stdout.write
>>> iter = each([1,2,3,4])
>>> iter()
1
>>> iter(lambda x: puts("Here's the next value: %s"x))
Here's the next value: 2
# small variant with block accepting two arguments
@accept_block
def each_and_succ(l):
for i in l:
yield i,i+1
>>> iter = each_and_succ([1,2,3,4])
>>> iter()
1,2
>>> iter(lambda x,y: puts("Next value: %s and its successor %s"%(x,y))
"Next value: 2 and its successor 3"
sum = 0
newlist = map(range(0,10)) def (x):
sum += x
return sum
> sum = 0
> newlist = map(range(0,10)) def (x):
> sum += x
> return sum
newlist = map(f, range(10)) with:
def f(x):
global sum
sum+=x
return sum
> sum = 0
> newlist = map(range(0,10)) def (x):
> sum += x
> return sum
> sum = 0
> > newlist = map(range(0,10)) def (x):
> > sum += x
> > return sum
button.Clicked += def():
print "somebody clicked me"
def initialize(self):
some_object.set_callback(self.callback)
def self.callback(self):
<callback goes here>
newlist = map(f, range(10)) with:
def f(x):
global sum
sum+=x
return sum
#===================
a = map( f, [1,2,3] ) in:
def f(n):
print n
return n+1
#====================
def add_funcs( f1, f2, arg ):
return f1( arg ) + f2( arg )
sum = add_funcs( f1, f2, 5 ) in:
def f1(n):
return n+1
def f2(n):
return n**n
#======================
# Or even thus:
sum = add_funcs( f1, f2, 5 ) in:
def f1(n):
return n+1
def f2(n):
return n**n
def add_funcs( f1, f2, arg ):
return f1( arg ) + f2( arg )
#=======================
map( f, range(10) ) in:
def f(n):
print n,'*',n,'=',n*n
#=======================