- Last edited October 29, 2002 |
www-106.ibm.com/developerworks/library/l-pycon.html?t=gr,lnxw06=PyIntro
Does anyone know the rationale behind doing this rather than a 'SmallTalk block' type approach (now that the scoping rules have been fixed in Python). I have included some code to show both approaches (needs Python 2.2) ? IvanM
from __future__ import generators
class Node: pass
a=Node() a.left=Node() a.value='d' a.right=Node() a.right.left=None a.right.right=None a.right.value='e' a.left.value='b' a.left.left=Node() a.left.right=Node() a.left.left.left=None a.left.left.right=None a.left.left.value='a' a.left.right.left=None a.left.right.right=None a.left.right.value='c'
#generator way
def walk(tree): if tree==None: return for n in walk(tree.left): yield n yield tree.value for n in walk(tree.right): yield n
print 'using generator' for n in walk(a): print n
#'smalltalk block' way
def do(tree,block): if tree==None: return do(tree.left, block) block(tree.value) do(tree.right, block)
def prn(x): print x
print 'using smalltalk block style' do(a, prn)
- Last edited October 29, 2002 |