Skip to content

Commit 405b026

Browse files
committed
little schemer c9
1 parent 2c3a0b6 commit 405b026

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

src/little-schemer/c9.scm

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
(define (atom? x)
2+
(and (not (pair? x)) (not (null? x))))
3+
4+
; pair is consisted of two s-expressions
5+
; different from pair?
6+
(define (a-pair? x)
7+
(cond ((atom? x) #f)
8+
((null? x) #f)
9+
((null? (cdr x)) #f)
10+
((null? (cdr (cdr x))) #t)
11+
(else #f)))
12+
13+
(define looking
14+
(lambda (a lat)
15+
(keep-looking a (pick 1 lat) lat)))
16+
17+
(define (pick n lat)
18+
(cond ((and (= n 1)
19+
(not (null? lat)))
20+
(car lat))
21+
((= n 1)
22+
(error 'pick "lat is null"))
23+
(else
24+
(pick (- n 1)
25+
(cdr lat)))))
26+
27+
(define (keep-looking a sorn lat)
28+
(cond ((number? sorn)
29+
(keep-looking a (pick sorn lat) lat))
30+
(else
31+
(eq? a sorn))))
32+
33+
; build s1 and s2 into a list
34+
(define (build s1 s2)
35+
(cons s1 (cons s2 '())))
36+
37+
(define (first pair)
38+
(car pair))
39+
40+
(define (second pair)
41+
(cadr pair))
42+
43+
(define (shift pair)
44+
(build (first (first pair))
45+
(build (second (first pair))
46+
(second pair))))
47+
48+
; pora is a special pair of an atom. The special pair is a pair
49+
; consisted of two special pair or atom.
50+
; Example:
51+
; '((1 2) ((3 4) (5 6)))
52+
; align it
53+
; '(1 (2 (3 (4 (5 6)))))
54+
(define (align pora)
55+
(cond ((atom? pora) pora)
56+
((a-pair? (first pora))
57+
(align (shift pora)))
58+
(else (build (first pora)
59+
(align (second pora))))))
60+
61+
(define (weight* pora)
62+
(cond ((atom? pora) 1)
63+
(else
64+
(+ (* (weight* (first pora)) 2)
65+
(weight* (second pora))))))
66+
67+
68+
; reverse a pair
69+
(define (revpair p)
70+
(build (second p) (first p)))
71+
72+
(define (shuffle pora)
73+
(cond ((atom? pora) pora)
74+
((a-pair? (first pora))
75+
(shuffle (revpair pora)))
76+
(else (build (first pora)
77+
(shuffle (second pora))))))

0 commit comments

Comments
 (0)