-
Notifications
You must be signed in to change notification settings - Fork 128
/
mut-y.ss
97 lines (81 loc) · 2.31 KB
/
mut-y.ss
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
96
;; deriving a "Y combinator" for mutual recursion
(define even
(lambda (x)
(cond
[(zero? x) #t]
[(= 1 x) #f]
[else (odd (sub1 x))])))
(define odd
(lambda (x)
(cond
[(zero? x) #f]
[(= 1 x) #t]
[else (even (sub1 x))])))
;; Step 1: package up functions, make a copy, create a cycle
(let ([p ((lambda (eo)
(cons
(lambda (x)
(cond
[(zero? x) #t]
[(= 1 x) #f]
[else ((cdr (eo eo)) (sub1 x))]))
(lambda (x)
(cond
[(zero? x) #f]
[(= 1 x) #t]
[else ((car (eo eo)) (sub1 x))]))))
(lambda (eo)
(cons
(lambda (x)
(cond
[(zero? x) #t]
[(= 1 x) #f]
[else ((cdr (eo eo)) (sub1 x))]))
(lambda (x)
(cond
[(zero? x) #f]
[(= 1 x) #t]
[else ((car (eo eo)) (sub1 x))])))))])
(let ([even (car p)]
[odd (cdr p)])
(even 21)))
;; Step 2: extract the outer self-application pattern
(let ([p ((lambda (x) (x x))
(lambda (eo)
(cons
(lambda (x)
(cond
[(zero? x) #t]
[(= 1 x) #f]
[else ((cdr (eo eo)) (sub1 x))]))
(lambda (x)
(cond
[(zero? x) #f]
[(= 1 x) #t]
[else ((car (eo eo)) (sub1 x))])))))])
(let ([even (car p)]
[odd (cdr p)])
(even 22)))
;; Step 3: extract inner self-application pattern
(let ([p ((lambda (x) (x x))
(lambda (eo)
(cons
(lambda (x)
((lambda (y)
(cond
[(zero? x) #t]
[(= 1 x) #f]
[else ((cdr y) (sub1 x))]))
(eo eo)))
(lambda (x)
((lambda (y)
(cond
[(zero? x) #f]
[(= 1 x) #t]
[else ((car y) (sub1 x))]))
(eo eo))))))])
(let ([even (car p)]
[odd (cdr p)])
(even 22)))
;; Oh no~ The nice form of Y combinator doesn't seem to work for
;; mutual recursion! backtrack to Step 2 would be close enough.