-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 1.43 repeated.rkt
executable file
·95 lines (82 loc) · 1.89 KB
/
Exercise 1.43 repeated.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
86
87
88
89
90
91
92
93
94
95
#lang racket
; Exercise 1.43. If f is a numerical function and n is a positive integer, then we can form
; the nth repeated application of f, which is defined to be the function whose value at x is
; f(f(...(f(x))...)). For example, if f is the function x -> x + 1, then the nth repeated
; application of f is the function x -> x + n. If f is the operation of squaring a number,
; then the nth repeated application of f is the function that raises its argument to the
; 2^nth power. Write a procedure that takes as inputs a procedure that computes f and a
; positive integer n and returns the procedure that computes the nth repeated application of
; f. Your procedure should be able to be used as follows:
; ((repeated square 2) 5)
; 625
; Hint: You may find it convenient to use compose from exercise 1.42.
; SOLUTION
(define (repeated f n)
(cond
((> n 1) (compose f (repeated f (- n 1))))
((= n 1) f)
(else
identity
)
)
)
(define (identity x)
x
)
(define (compose f g)
(lambda (w) (f (g w)))
)
(define (cube x)
(* x x x)
)
(define (square x)
(* x x)
)
(define (double f)
(lambda (w) (f (f w)))
)
(define (inc x)
(+ x 1)
)
; Tests
> ((repeated square 0) 5)
5
> ((repeated square 1) 5)
25
> ((repeated square 2) 5)
625
> ((repeated square 3) 5)
390625
> ((repeated square 4) 5)
152587890625
> ((repeated inc 0) 5)
5
> ((repeated inc 1) 5)
6
> ((repeated inc 2) 5)
7
> ((repeated inc 3) 5)
8
> ((repeated inc 10) 5)
15
> ((repeated inc 100) 5)
105
> ((repeated inc -1) 5)
5
> ((repeated sin 2) 5)
-0.8185741444617193
> ((repeated cube 0) 5)
5
> ((repeated cube 1) 5)
125
> ((repeated cube 0) 7)
7
> ((repeated cube 1) 7)
343
> ((repeated cube 2) 7)
40353607
> ((repeated cube 4) 7)
283753509180010707824461062763116716606126555757084586223347181136007
> ((repeated cube 3) 7)
65712362363534280139543
>