20-CS-4003-001 Organization of Programming Languages Fall 2017
Additional Scheme Procedures

Lambda calculus, Type theory, Formal semantics, Program analysis

    Back     All lectures

Some Scheme Warmups

;;; Simple curry - invoke f1 once with an op argument to get another procedure.

  (define f1 (lambda (x) (lambda (y) (lambda (z) (x y z)))))

(f1 +)

((f1 +) 3)

(((f1 +) 3) 2)

;;; Invoke f2 once with an op argument to get another procedure that applies it to two arguments.

  (define f2 (lambda (x) (lambda (y z) (x y z))))

;;; Here is another way to do it using letrec

  (define f3
    (lambda (x)
      (letrec ((r (lambda (y z) (x y z))))
        r)))

;;; Several functions may be letrec'ed

  (define f4
    (lambda (x y)
      (letrec ((r1 (lambda (z) (x z 10)))
               (r2 (lambda (w) (y w 5))))
        (lambda (q) (r2 (r1 q))))))

;;; Simple Recursion

  (define fact (lambda (n) (if (= n 1) 1 (* n (fact (- n 1))))))

(fact 10)

;;; Another way to do this

  (define fact1
    (lambda l
      (if (= (car l) 1)
          1
          (* (car l) (fact1 (- (car l) 1))))))

;;; Use all this to create functions that take any number of arguments
;;; Example: simple addition

  (define add
    (lambda l
      (letrec ((a (lambda (x)
                    (if (null? x)
                        0
                        (if (null? (cdr x))
                            (car x)
                            (+ (car x) (a (cdr x))))))))
        (a l))))

;;; Turn any binary function into a function of lots of arguments - (R-L assoc)

  (define fr-maker
    (lambda (op)
      (lambda l
        (letrec ((a (lambda (x)
                      (if (null? x)
                          0
                          (if (null? (cdr x))
                              (car x)
                              (op (car x) (a (cdr x))))))))
          (a l)))))

;;; Turn any binary function into a function of lots of arguments - (L-R assoc)

  (define fl-maker
    (lambda (op)
      (lambda l
        (letrec ((a (lambda (x acc)
                      (if (null? x)
                          acc
                          (a (cdr x) (op acc (car x)))))))
          (a (cdr l) (car l))))))