20-CS-4003-001 Organization of Programming Languages Fall 2017
Lambda

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code     Supplementary examples

Lambda Expressions and Procedures

 
(let* ((v1 (lambda () 2))  -  v1 is an expression of no arguments, returns 2
1111111(v2 (lambda (x) (+ x 2)))  -  v2 adds 2 to its argument x when invoked
1111111(v3 (lambda (x y) (+ x y)))  -  v3 is a procedure for adding two numbers
1111111(v4 (lambda (x)  -  v4 is a procedure that returns a procedure
1111111111111(lambda (y z)    of two arguments. The returned procedure applies
1111111111111111(x y z)))))    the operation passed by the outer lambda to the arguments of the inner lambda
111(list (v1) (v2 42) (v3 1 2) (v4 cons)))
 
(define f1 
   (lambda (x) 
      (if (= x 0) 
          '() 
          (cons x (f1 (- x 1))))))
 -  f1 takes an integer as input and returns a list of consecutive integers from the input integer down to 1. If a negative integer is input scheme attempts to create an infinite list but stops with the error
   ;Aborting!: maximum recursion depth exceeded
 
(define f2
   (lambda (x)
      (if (= x 0)
          '()
          (append (f2 (- x 1))
                  (list x)))))
 -  f2 takes an integer as input and returns a list of consecutive integers from 1 to the input integer. If a negative integer is input scheme attempts to create an infinite list but stops with the error
   ;Aborting!: maximum recursion depth exceeded
 
(define f3*
   (lambda (x lst)
      (if (= x 0)
          lst
          (f3* (- x 1)
               (cons x lst)))))

(define f3
   (lambda (x) (f3* x '())))
 -  f3 takes an integer as input and returns a list of consecutive integers from 1 to the input integer. It calls f3* so the caller does not have to worry about inputting a '(). The procedure f3* is tail recursive so nothing is stacked. However, if a negative integer is input scheme attempts to create an infinite list but stops with the error
   ;Aborting!: out of memory
   ;GC #18: took: 0.30  (12%) CPU time, 0.40 (14%) real time; free: 4192895
   ;GC #19: took: 0.30 (100%) CPU time, 0.30 (94%) real time; free: 4192953
because the list it is building becomes too large.