You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

Lambda Functions

Lambda functions are actually the fundamental way in which Scheme defines a function:

(define (myFunc x y)
   (...))

is really just a Scheme shorthand for

(define myFunc (lambda (x y)
   (...)))

The only reason we ever give associate a name with something is if we wish to reference it more than once!

This means that everything that we done with functions already also applies to lambdas, since they are all the same thing.

The lambda function definition is useful when we want to define a function right where we use it.   (Most likely because we only need to use that function once.)

For instance, lambdas are very useful when a function is needed as an input parameter, such as when calling higher-order functions, e.g. filter, map, foldr, etc.:

(filter (lambda (x) (...)) aList)

(map (lambda (x) (...)) aList)

(foldr (lambda (aFirst aRecursiveResult)(...)) aList)

Lambdas are also useful when a function is needed for a return value:

;; make-addX: num -> (lambda num -> num)
;; returns a function that adds its input to the original x input.
;; Examples:
(check-expect ((make-addX 3) 5) 8)
(check-expect ((make-addX 3) -2) 1)
(check-expect ((make-addX -5) 5) 0)
(check-expect ((make-addX -5) -2) -7)
(define (make-addX x)
   (lambda (y) (+ x y))) 

Problem: A "pure" lambda cannot be recursive because it cannot refer to itself!   This issue can be solved using more sophisticated lambda function techniques, which are mostly out of the scope of this course, and in Java, which always defines a name for object to use to reference itself.  

  • No labels