; as written, these procedures from the reading only sort lists of numbers and only ; in ascending order ; if we change <= to string<=? in the insert procedure, then insertion sort will ; sort strings in alphabetical order ;(define insert ; (lambda (new-element ls) ; (cond ((null? ls) (list new-element)) ; ((string<=? new-element (car ls)) (cons new-element ls)) ; (else (cons (car ls) (insert new-element (cdr ls))))))) ; ;(define insertion-sort ; (lambda (unsorted) ; (if (null? unsorted) ; null ; (insert (car unsorted) (insertion-sort (cdr unsorted)))))) ; I would like to make a more general procedure, which I tell the way to sort ; and it returns a procedure that sorts that way (like procedures-as-values reading/lab ; we will pass in a boolean procedure which returns #t is the first input can come ; before the second, like for example, <=, string<=?, ...., we call this MAY-PRECEDE? (define generic-sort (lambda (may-precede?) (letrec ((insert (lambda (new-element ls) (cond ((null? ls) (list new-element)) ((may-precede? new-element (car ls)) (cons new-element ls)) (else (cons (car ls) (insert new-element (cdr ls))))))) (insertion-sort (lambda (unsorted) (if (null? unsorted) null (insert (car unsorted) (insertion-sort (cdr unsorted))))))) insertion-sort))) (define ascending-numerical-sort (generic-sort <=)) (define descending-numerical-sort (generic-sort >=)) (define alphabetical-sort (generic-sort string<=?)) ; for example (alphabetical-sort '("Martha" "DL" "Thomas" "Samantha" "Kate" "Dan")) ; returns ("DL" "Dan" "Kate" "Martha" "Samantha" "Thomas") ; in fact in some case, our may-precede? may need to be more exciting... (define name-list '(("Thomas" "Alexander") ("Ananta" "Tiwari") ("Kate" "Kearney") ("Dan" "Jones") ("Seth" "Heller"))) ; what may-precede? do I give to generic-sort to sort this list of names by last ; name? (define last-name-sort (generic-sort (lambda (name1 name2) (string<=? (cadr name1) (cadr name2))))) ; to sort by first name, we do the same thing but with the (car name) (define first-name-sort (generic-sort (lambda (name1 name2) (string<=? (car name1) (car name2))))) ; now let's try this out with (last-name-sort name-list) (first-name-sort name-list)