1. Computing

Using Lambda Calculus in Python

By

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:
def substitute(x)
     return x = x.replace(x, y)
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".

  1. About.com
  2. Computing
  3. Python
  4. Beginning Python
  5. Python Programming - Beginning Python- Functions - Lambda Functions

©2014 About.com. All rights reserved.