Friday, 5 October 2012

Why lambda?

In an functional programming it is not sufficient to define small trivial functions for lower level operations, rather these functions can be used as an argument. The most convenient way to define a function to associate a variable to a particular operation without bounding to a particular identifier is to use lambda.

                                 A lambda expression evaluates to a procedure. The environment in effect when the lambda expression is evaluated is remembered as part of the procedure; it is called the closing environment. When the procedure is later called with some arguments, the closing environment is extended by binding the variables in the formal parameter list to fresh locations, and the locations are filled with the arguments according to rules about to be given. The new environment created by this process is referred to as the invocation environment.

One way to accomplish this is to use an auxiliary procedure to bind the local variables:


(define (f x y)
  (define (f-helper a b)
    (+ (* x (square a))
       (* y b)
       (* a b)))
  (f-helper (+ 1 (* x y)) 
            (- 1 y)))


 By using lambda for the example then the body of f becomes a single call to the procedure.

(define (f x y)
  ((lambda (a b)
     (+ (* x (square a))
        (* y b)
        (* a b)))
   (+ 1 (* x y))
   (- 1 y)))

The lambda is also known as an anonymous functions since it doesn't spoil the name space by unnecessary definition of named functions.  

No comments:

Post a Comment