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 ;abs-sort : (number number -> boolean) -> ((listof number) -> (listof number))
7 ;Given the operator, which determines whether to sort ascending or descending, abs-sort returns a sort function that sorts a (listof numbers).
9 (define (abs-sort operator)
10 (local ((define (sort alon)
11 (local ((define (sort alon)
12 (cond
13 [(empty? alon) empty]
14 [else (insert (first alon) (sort (rest alon)))]))
15 (define (insert an alon)
16 (cond
17 [(empty? alon) (list an)]
18 [else (cond
19 [(operator an (first alon)) (cons an alon)]
20 [else (cons (first alon) (insert an (rest alon)))])])))
21 (sort alon))))
22 sort))
24 ;sort-ascend : (listof numbers) -> (listof numbers)
25 ;Given a-lon, return a list-of-numbers sorted in ascending order.
26 (define sort-ascend (abs-sort <))
28 ;sort-descend : (listof numbers) -> (listof numbers)
29 ;Given a-lon, return a list-of-numbers sorted in descending order.
30 (define sort-descend (abs-sort >))
32 ;abs-fold : (X Y -> Y) -> ((listof X) -> Y)
33 ;Given operator and base, return the fold function with operator filled in.
35 (define (abs-fold operator base)
36 (local ((define (fold alon)
37 (cond
38 [(empty? alon) base]
39 [else (operator (first alon)
40 (fold (rest alon)))])))
41 fold))
43 (define sum (abs-fold + 0))
44 (define product (abs-fold * 1))