20-CS-4003-001 Organization of Programming Languages Fall 2017
Object Oriented Style

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

A stack "class"

;; -----------------------------
;;   Stacks

(define stack
  (lambda (s)
    (lambda msg
      (letrec 
        ((push (lambda (x) (stack (cons x s))))
         (pop (lambda () (stack (cdr s))))
         (peek (lambda () (car s)))
         (show (lambda () s)))
        (case (car msg)
          ('peek   (peek))
          ('push  (push (car (cdr msg))))
          ('pop   (pop))
          ('show  (show))
          (else   '()))))))

;; -------------------------------
;;  Tests

(define destroy-stack
  (lambda (s)
    (if (null? (s 'show))
        '()
        (cons (s 'show)
              (destroy-stack (s 'pop))))))

(define build-stack
  (lambda (s n)
    (if (= n 0)
        '()
        (cons (s 'show) 
              (build-stack (s 'push n) (- n 1))))))

(define build-and-destroy-stack
  (lambda (s n)
    (letrec 
      ((bs (lambda (s^ n^) 
             (if (= n^ 0) 
                 s^ 
                 (bs (s^ 'push n^) (- n^ 1))))))
      (append (build-stack s n) 
              (destroy-stack (bs s n))))))
 -  The code to the left has the effect of defining a "stack" class. The methods push, pop, peek are implemented as procedures that contain the contents of the stack. A stack is created using
   prompt> (define st (stack '()))
The object st is now a procedure that accepts any one of four tokens and performs the appropriate operation. The argument '() given to stack initializes the stack to '() - any other list would work just as well in initializing the stack to something else and this is what happens when an object is pushed or popped. For example
   prompt> ((((st 'push 34) 'push 23) 'push 42) 'show)
   ;Value 34: (42 23 34)
When a destructive operation is performed, a new stack is created from a cons or a cdr of the current stack list s and returned. The double lambda makes this straightforward. Try this:
   prompt> (build-stack (stack '()) 10)
   ;Value 16: (() (10) (9 10) (8 9 10) (7 8 9 10) 
   (6 7 8 9 10) (5 6 7 8 9 10) (4 5 6 7 8 9 10) 
   (3 4 5 6 7 8 9 10) (2 3 4 5 6 7 8 9 10))