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 21.1.2) (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 #|
6 Exercise 21.1.2. Define fold, which is the abstraction of the following two functions:
8 ;; sum : (listof number) -> number
9 ;; to compute the sum of
10 ;; the numbers on alon
11 (define (sum alon)
12 (cond
13 [(empty? alon) 0]
14 [else (+ (first alon)
15 (sum (rest alon)))]))
17 ;; product : (listof number) -> number
18 ;; to compute the product of
19 ;; the numbers on alon
20 (define (product alon)
21 (cond
22 [(empty? alon) 1]
23 [else (* (first alon)
24 (product (rest alon)))]))
25 Don't forget to test fold.
26 After fold is defined and tested, use it to define append, which juxtaposes the items of two lists or, equivalently, replaces empty at the end of the first list with the second list:
28 (equal? (append (list 1 2 3) (list 4 5 6 7 8))
29 (list 1 2 3 4 5 6 7 8))
30 Finally, define map using fold.
32 Compare the four examples to formulate a contract. Solution
34 |#
36 ;fold : (X Y -> Y) (listof X) Y -> Y
37 ;Given op and alox, return the value of op applied cumulatively on every value in alox. The value base specifies a value that is the base from which fold operates upon.
39 (define (fold op alox base)
40 (cond
41 [(empty? alox) base]
42 [else (op (first alox) (fold op (rest alox) base))]))
44 ;sum : (listof number) -> number
45 ;Given alon, adds all the numbers in the list.
46 (define (sum alon)
47 (fold + alon 0))
49 ;product : (listof number) -> number
50 ;Given alon, multiplies all the numbers in the list.
51 (define (product alon)
52 (fold * alon 1))
54 ;append : (listof X) (listof Y)
55 ;Given list1 and list2, append list2 to the end of list1.
56 (define (append! list1 list2)
57 (fold cons list1 list2))
59 (append! '(Hi my name is Joe) '(Hi my name is Aaron))