Let's Talk About Lambda Functions!

Miki Tebeka tebeka at cs.bgu.ac.il
Tue Aug 6 10:21:18 CEST 2002


Hello Brit,

> So I know what lambda functions are, they're syntax and how they're used.
> However I'm not sure *why* one would use a lambda function. What's the
> advantage that they offer over a regular function?

Warning: I've bee a Scheme believer before I've converted to Python
:-)

Sometime lambda functions yeild more (IMO) elegant solution that is 
easier to read and understand.
One example is success/fail continuations.

---------
# Demonstrate success/fail continuation
class Tree:
    '''Simple binary tree'''
    def __init__(self, val, lson=None, rson=None):
        self.val = val
        self.lson = lson
        self.rson = rson

    def display(self, indent = 0):
        print '  ' * indent, self.val
        if self.lson:
            self.lson.display(indent + 1)
        if self.rson:
            self.rson.display(indent + 1)
        
        

# We'd like to find the path we need to take in 'left', 'right' steps
# in order to get to a certain node in a tree

def path2(t, v):
    '''Find path to v in t'''
    return sfpath2(t, v, lambda v: v, lambda: 'Not Found') # Call with
initial continuations

def sfpath2(t, v, success, fail):
    '''Success/Fail continuation solution'''
    if not t:
        return fail() # Can't find
    if t.val == v: # Found right here
        return success([])
    # Recursive case, update success/fail continuations
    return sfpath2(t.lson, v, 
                    lambda v: success(['left'] + v), 
                    lambda: sfpath2(t.rson, v, lambda v:
success(['right'] + v), fail))

# -- testing
t = Tree(1,
        Tree(2,
            Tree(3)),
        Tree(4,
            Tree(5)))

t.display()

print '* Path to 5'
print path2(t, 5)

print '* Path to 10'
print path2(t, 10)
---------

Miki



More information about the Python-list mailing list