20-CS-4003-001 Organization of Programming Languages Fall 2017
Basic Operations

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code


; Split: input is a list of objects, output is a list of two lists of
;   approximately equal size such that the set of all objects in both
;   lists is the same as the set of objects in the input list.
(define split
  (lambda (l)
    (if (null? l)
        (list '() '())
        (if (null? (cdr l))
            (list l '())
            (let ((rest (split (cddr l))))
              (list (cons (car l) (car rest))
                    (cons (car (cdr l))
                          (car (cdr rest)))))))))

; Merge: input is two lists of numbers in increasing order, output is
;   a list of numbers in increasing order consisting of exactly those
;   numbers in the input list.
(define merge
  (lambda (l1 l2)
    (if (null? l1)
        (if (null? l2)
            (if (< (car l1) (car l2))
                (cons (car l1) (merge (cdr l1) l2))
                (cons (car l2) (merge l1 (cdr l2))))))))

; Merge-sort: input is a list of numbers, output is that list sorted
(define mrgsrt
  (lambda (lst)
    (if (null? lst)
        (if (null? (cdr lst))
            (let* ((s (split lst))
                   (a (car s))
                   (b (cadr s)))
              (merge (mrgsrt a) (mrgsrt b)))))))