-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex-1-16.scm
69 lines (61 loc) · 1.67 KB
/
ex-1-16.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
58
59
60
61
62
63
64
65
66
67
;;; 1
;;; <list-of-symbols> ::= ()
;;; ::= (<symbol> . <list-of-symbols>))
;;; <slist2> ::= ()
;;; ::= (<symbol-expression2> . <slist2>)
;;; <symbol-expression2> ::= <symbol> | <list-of-symbols>
(define up
(lambda (lst) ; an slist2
(if (null? lst)
'()
(if (symbol? (car lst)); (car lst) will be either a symbol or a list of symbols
(cons (car lst) (up (cdr lst)))
(up-los (car lst) (up (cdr lst)))))))
(define up-los ; This is basically a special purpose append
(lambda (lst tl) ; a list-of-symbols
(if (null? lst)
tl
(cons (car lst) (up-los (cdr lst) tl)))))
;;; 2
(define swapper
(lambda (s1 s2 slist)
(if (null? slist)
'()
(let ((se (car slist)))
(if (symbol? se)
(cons (swap s1 s2 se) (swapper s1 s2 (cdr slist)))
(cons (swapper s1 s2 se) (swapper s1 s2 (cdr slist))))))))
(define swap
(lambda (s1 s2 s)
(if (eqv? s1 s)
s2
(if (eqv? s2 s)
s1
s))))
;;; 3
(define count-occurences-iter
(lambda (s slist n)
(if (null? slist)
n
(let ((front (car slist))
(back (cdr slist)))
(if (symbol? front)
(if (eqv? s front)
(count-occurences-iter s back (+ n 1))
(count-occurences-iter s back n))
(count-occurences-iter s back (+ n (count-occurences-iter s front 0))))))))
(define count-occurences
(lambda (s slist)
(count-occurences-iter s slist 0)))
;;; 4
(define flatten
(lambda (slist)
(if (null? slist)
'()
(let ((se (car slist))
(rst (cdr slist)))
(if (symbol? se)
(cons se (flatten rst))
(if (null? (cdr se))
(cons (car se) (flatten rst))
(cons (car se) (flatten (cons (cdr se) rst)))))))))