-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 2.33 accumulate operations.rkt
executable file
·85 lines (74 loc) · 1.56 KB
/
Exercise 2.33 accumulate operations.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#lang racket
; Exercise 2.33. Fill in the missing expressions to complete the following definitions of
; some basic list-manipulation operations as accumulations:
; (define (map p sequence)
; (accumulate (lambda (x y) <??>) nil sequence))
; (define (append seq1 seq2)
; (accumulate cons <??> <??>))
; (define (length sequence)
; (accumulate <??> 0 sequence))
; SOLUTION
(define (length sequence)
(accumulate
(lambda (x y)
(+ y 1)
)
0
sequence
)
)
(define (append seq1 seq2)
(accumulate cons seq2 seq1)
)
(define (map p sequence)
(accumulate
(lambda (x y)
(cons (p x) y)
)
null
sequence
)
)
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence) (accumulate op initial (cdr sequence)))
)
)
(define (inc x)
(+ x 1)
)
(define (square x)
(* x x)
)
; Tests
Welcome to DrRacket, version 6.11 [3m].
Language: racket, with debugging; memory limit: 128 MB.
> (define odds (list 1 3 5 7 9))
> odds
'(1 3 5 7 9)
> (inc 2)
3
> (map inc odds)
'(2 4 6 8 10)
> (map inc (map inc odds))
'(3 5 7 9 11)
> (map square odds)
'(1 9 25 49 81)
> (define evens (list 2 4 6 8 10))
> evens
'(2 4 6 8 10)
> (map square evens)
'(4 16 36 64 100)
> (map inc odds)
'(2 4 6 8 10)
> (append evens odds)
'(2 4 6 8 10 1 3 5 7 9)
> (append evens odds)
'(2 4 6 8 10 1 3 5 7 9)
> (append odds evens)
'(1 3 5 7 9 2 4 6 8 10)
> (append (map square odds) (map square evens))
'(1 9 25 49 81 4 16 36 64 100)
> (length (append (map square odds) (map square evens)))
10