-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathex1.43-procedure-repeated.scm
60 lines (42 loc) · 1.16 KB
/
ex1.43-procedure-repeated.scm
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
(define (inc x)
(+ x 1))
(define (compose f g)
(lambda (x) (f (g x))))
(define (repeated g n)
(if (= n 1)
g
(lambda (x) ((repeated g (- n 1)) (g x)))))
; Manual iteration:
;=============
((repeated square 2) 5) ; 625
;| |
( (lambda (x) ((repeated square 1) (square x))) 5)
; | |
( (lambda (x) (square (square x))) 5)
((repeated square 3) 5) ; 390625
;| |
( (lambda (x) ((repeated square 2) (square x))) 5)
; | |
( (lambda (x) ( (lambda (x) ((repeated square 1) (square x))) (square x))) 5)
( (lambda (x) ( (lambda (x) (square (square x))) (square x))) 5)
( (lambda (x) ( (square (square (square x)))) ) 5)
;=================
; With compose:
(define (repeated g n)
(if (= n 1)
g
(compose (repeated g (- n 1)) g)))
; better:
(define (identity x) x)
(define (repeated g n)
(if (< n 1)
identity
(compose (repeated g (- n 1)) g)))
; With compose iterative:
(define (identity x) x)
(define (repeated g n)
(define (iter counter result)
(if (= counter 0)
result
(iter (- counter 1) (compose g result))))
(iter n identity))