Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Generating a C-style compare function

Here is a possible generation of the C-style compare function

(define (make-comparator lt) (lambda (e1 e2) (cond ((lt e1 e2) -1) ((lt e2 e1) 1) ; notice the trick: we used lt with arguments reordered. (else 0))))

It can used in the following ways:

  > (define strcmp (make-comparator string<?))

  > (strcmp "abe" "kat")

  > (strcmp "kat" "abe")

  > (strcmp "kat" "kat")

Here is a function that generates a list of a 'less than', 'equal to', and 'greater than' from a C-style compare function:

(define (lt-eq-gt cmp) (list (lambda (x y) (< (cmp x y) 0)) (lambda (x y) (= (cmp x y) 0)) (lambda (x y) (> (cmp x y) 0))))