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 19.1.5) (read-case-sensitive #t) (teachpacks ((lib "draw.ss" "teachpack" "htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "draw.ss" "teachpack" "htdp")))))
4 ;; mini : nelon -> number
5 ;; to determine the smallest number
6 ;; on alon
7 (define (mini alon)
8 (cond
9 [(empty? (rest alon)) (first alon)]
10 [else (cond
11 [(< (first alon)
12 (mini (rest alon)))
13 (first alon)]
14 [else
15 (mini (rest alon))])]))
17 ;; maxi : nelon -> number
18 ;; to determine the largest number
19 ;; on alon
20 (define (maxi alon)
21 (cond
22 [(empty? (rest alon)) (first alon)]
23 [else (cond
24 [(> (first alon)
25 (maxi (rest alon)))
26 (first alon)]
27 [else
28 (maxi (rest alon))])]))
30 ;A non-empty-list-of-numbers (nelon) is
31 ;1. (cons n empty)
32 ;2. (cons n ne)
33 ;where n is a number and ne is a non-empty-list-of-numbers (nelon).
34 ;
35 ;extrema : predicate nelon -> number
36 ;Given predicate and a-lon, return the extreme value depending on the predicate.
38 ;pick-interesting : predicate list-of-numbers
39 ;Given predicate and a-lon, pick the interesting (extreme) number.
41 (define (extrema predicate a-lon)
42 (cond
43 [(empty? (rest a-lon)) (first a-lon)]
44 [else (local ((define extrema-recursion (extrema predicate (rest a-lon)))
45 (define (pick-interesting predicate a-lon)
46 (cond
47 [(predicate (first a-lon) extrema-recursion) (first a-lon)]
48 [else extrema-recursion])))
49 (pick-interesting predicate a-lon))]))
51 ;mini1 : nelon -> number
52 ;Given a-lon, returns the minimum value.
53 (define (mini1 a-lon)
54 (extrema < a-lon))
56 ;maxi1 : nelon -> number
57 ;Given a-lon, returns the maximum value.
58 (define (maxi1 a-lon)
59 (extrema > a-lon))
61 ;(time (mini1 (list 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1)))
62 ;(time (maxi1 (list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20)))
64 ;; sort : list-of-numbers predicate -> list-of-numbers
65 ;; to construct a list with all items from alon in ascending or descending order
66 (define (sort1 alon predicate)
67 (local ((define (sort alon)
68 (cond
69 [(empty? alon) empty]
70 [else (insert (first alon) (sort (rest alon)))]))
71 (define (insert an alon)
72 (cond
73 [(empty? alon) (list an)]
74 [else (cond
75 [(predicate an (first alon)) (cons an alon)]
76 [else (cons (first alon) (insert an (rest alon)))])])))
77 (sort alon)))
79 ;sort-ascend : list-of-numbers
80 ;Given a-lon, return a list-of-numbers sorted in ascending order.
81 (define (sort-ascend alon)
82 (sort1 alon <))
84 ;sort-descend : list-of-numbers
85 ;Given a-lon, return a list-of-numbers sorted in descending order.
86 (define (sort-ascend alon)
87 (sort1 alon >))