Blob


1 ;; The first three lines of this file were inserted by DrScheme. They record metadata
2 ;; about the language level of this file in a form that our tools can easily process.
3 #reader(lib "htdp-intermediate-reader.ss" "lang")((modname |22.2|) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "draw.ss" "teachpack" "htdp") (lib "arrow.ss" "teachpack" "htdp")))))
4 Exercise 22.2.2. Define an abstract version of sort (see exercise 19.1.6) using the new recipe for abstraction. Solution
6 ;; sort : list-of-numbers predicate -> list-of-numbers
7 ;; to construct a list with all items from alon in ascending or descending order
8 (define (sort1 alon predicate)
9 (local ((define (sort alon)
10 (cond
11 [(empty? alon) empty]
12 [else (insert (first alon) (sort (rest alon)))]))
13 (define (insert an alon)
14 (cond
15 [(empty? alon) (list an)]
16 [else (cond
17 [(predicate an (first alon)) (cons an alon)]
18 [else (cons (first alon) (insert an (rest alon)))])])))
19 (sort alon)))
21 ;sort-ascend : list-of-numbers
22 ;Given a-lon, return a list-of-numbers sorted in ascending order.
23 (define (sort-ascend alon)
24 (sort1 alon <))
26 ;sort-descend : list-of-numbers
27 ;Given a-lon, return a list-of-numbers sorted in descending order.
28 (define (sort-ascend alon)
29 (sort1 alon >))
31 ;; sort : list-of-numbers -> list-of-numbers
32 ;; to construct a list with all items from alon in descending order
33 (define (sort alon)
34 (local ((define (sort alon)
35 (cond
36 [(empty? alon) empty]
37 [else (insert (first alon) (sort (rest alon)))]))
38 (define (insert an alon)
39 (cond
40 [(empty? alon) (list an)]
41 [else (cond
42 [(> an (first alon)) (cons an alon)]
43 [else (cons (first alon) (insert an (rest alon)))])])))
44 (sort alon)))