1. Home
  2. Computing & Technology
  3. Python

Using Lambda Calculus in Python

From , former About.com Guide

Prior to object-oriented programming and the creation of Python, one of the mainstays of computing was functional programming. For computer programming, a function is a calculus and might be defined as a set of results that are derived by performing a series of predictable manoeuvres on input matching certain characteristics or parameters. As noted in the tutorials for beginning Python, those parameters are the arguments of the function.

To design a mathematical function in pseudo-code, it is a good idea to default to lambda forms. For example, to square a given input x, the computation is x*x. But for lambda, we write the formal definition of the function:

λ x. x ⋅ x
This translates readily into Python:
def square(x):
    return lambda x: x*x
In this case, Python will automatically determine the numerical nature of the argument. However, you can define character-manipulating functions similarly. For example to define substitution, one would write:
λ x[y := x′]
This function equates to all x such that y is substituted for x. In Python, one writes: [blockquote] def substitute(x)
     return x = x.replace(x, y) [/blockquote] An example shell session that shows the flexibility of the replace string function follows:
>>> x = 'cat'
>>> y = 'dog'
>>> x = x.replace(x, y)
>>> x
'dog'
>>> x = x.replace('o', y)
>>> x
'ddogg'
The virtue of using lambda notation to design functions is pretty plain. However, for more on functions, see "Beginning Python: Putting It All Together With Syntax".

More Python Quick Tips
Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python
  4. Beginning Python
  5. Python Programming - Beginning Python- Functions - Lambda Functions

©2009 About.com, a part of The New York Times Company.

All rights reserved.