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

N-ary operations: right/left association

;;---------------------------------------------------
;;  Abstract to any operation with right association

(define extended-op-maker-R
  (lambda (op)
    (lambda l
      (letrec
        ((eop
           (lambda (l^)
             (if (null? l^)
                 'error-no-args-not-allowed
                 (if (null? (cdr l^))
                     (car l^)
                     (op (car l^) (eop (cdr l^))))))))
        (eop l)))))

(define f (extended-op-maker-R *))
(define g (extended-op-maker-R +))
(define h (extended-op-maker-R cons))
(define i (extended-op-maker-R /))

;; --------------------------------------------------
;;  Do the same for operations with left association

(define extended-op-maker-L
  (lambda (op)
    (lambda l
      (letrec
        ((eop
           (lambda (l^ acc)
             (if (null? l^)
	         acc
                 (eop (cdr l^) (op acc (car l^)))))))
        (if (null? l)
	    'error
	    (eop (cdr l) (car l)))))))

(define j (extended-op-maker-L /))
(define k (extended-op-maker-L cons))
 -  The code to the left generalizes the code from the previous slide so that any binary operator can be extended to an n-ary operator. The first procedure applies to operators that are right associative. Most operators, for example +, can associate to the left or the right without a change in value but some may have different results depending on the order in which the arguments are processed. The operator cons only makes sense when evaluating arguments from right to left. Try this:
   prompt> (define econs (extended-op-maker-R cons))
   prompt> (econs 'a 'b 'c 'd 'e '())
   ;Value 12: (a b c d e)
The second procedure results in operators that associate from the left. Try this:
   prompt> (define lcons (extended-op-maker-L cons))
   prompt> (lcons 'a 'b 'c 'd 'e '())
   ;Value 14: (((((a . b) . c) . d) . e))
What happens if you do this:
   prompt> (define qcons (extended-op-maker-R lcons))