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

Lambda calculus, Type theory, Formal semantics, Program analysis

Prev     Next     All lectures        Code

Extending to n-ary operations

 ```;; ----------------------------------------------------- ;; Make two argument operation an n argument operation ;; The plus operation (define extended-plus (lambda (l) (if (null? l) 'error-no-args-not-allowed (if (null? (cdr l)) (car l) (+ (car l) (extended-plus (cdr l))))))) '(+ '(1 2 3 4)) ;; ----------------------------------------- ;; The plus operation with letrec (define ep (lambda l (letrec ((op (lambda (l^) (if (null? l^) 'error-no-args-not-allowed (if (null? (cdr l^)) (car l^) (+ (car l^) (op (cdr l^)))))))) (op l)))) '(+ 1 2 3 4) ;; -------------------------------------- ;; The times operation (define et (lambda l (letrec ((op (lambda (l^) (if (null? l^) 'error-no-args-not-allowed (if (null? (cdr l^)) (car l^) (* (car l^) (op (cdr l^)))))))) (op l)))) ``` - Any binary operation can be extended to an n-ary operation. The first procedure to the left illustrates this by extending the + operator. However, the result is awkward because it requires a separate list for the arguments, for example like this: ``` (extended-plus '(1 2 3 4)) ``` This is corrected in the second procedure by putting the recursive code for walking through all the arguments into a letrec and changing (lambda (l) to (lambda l. The procedure in the letrec, called op, is invoked with (op l). Now the following can be done: ``` (ep 1 2 3 4) ``` The third procedure does the same for times: ``` (et 1 2 3 4) ```