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")
  -1

  > (strcmp "kat" "abe")
  1

  > (strcmp "kat" "kat")
  0

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))))