forked from tommyfan34/cs61a
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestions.scm
executable file
·103 lines (87 loc) · 2.87 KB
/
questions.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
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
97
98
99
100
101
102
103
(define (caar x) (car (car x)))
(define (cadr x) (car (cdr x)))
(define (cdar x) (cdr (car x)))
(define (cddr x) (cdr (cdr x)))
; Some utility functions that you may find useful to implement
(define (zip pairs)
'replace-this-line)
;; Problem 15
;; Returns a list of two-element lists
(define (enumerate s)
; BEGIN PROBLEM 15
(begin (define (helper index s)
(cond ((null? s) s)
(else (cons (cons index (cons (car s) nil)) (helper (+ 1 index) (cdr s))))))
(helper 0 s))
)
; END PROBLEM 15
;; Problem 16
;; Merge two lists LIST1 and LIST2 according to COMP and return
;; the merged lists.
(define (merge comp list1 list2)
; BEGIN PROBLEM 16
(cond ((null? list1) list2)
((null? list2) list1)
((comp (car list1) (car list2)) (cons (car list1) (merge comp (cdr list1) list2)))
(else (cons (car list2) (merge comp list1 (cdr list2)))))
)
; END PROBLEM 16
(merge < '(1 5 7 9) '(4 8 10))
; expect (1 4 5 7 8 9 10)
(merge > '(9 7 5 1) '(10 8 4 3))
; expect (10 9 8 7 5 4 3 1)
;; Problem 17
(define (nondecreaselist s)
; BEGIN PROBLEM 17
(cond (
((null? (cdr s)) (cons s nil))
((> (car s) (car (cdr s))) (cons (cons (car s) nil) (nondecreaselist (cdr s))))
(else (cons (cons (car s) (car (nondecreaselist (cdr s)))) (cdr (nondecreaselist (cdr s))))))
)
)
; END PROBLEM 17
(define (zip s)
(cond ((null? s) '(() ()))
(else (cons (cons (car (car s)) (car (zip (cdr s)))) (cons (cons (car (cdr (car s))) (car (cdr (zip (cdr s))))) nil))))
)
;; Problem EC
;; Returns a function that checks if an expression is the special form FORM
(define (check-special form)
(lambda (expr) (equal? form (car expr))))
(define lambda? (check-special 'lambda))
(define define? (check-special 'define))
(define quoted? (check-special 'quote))
(define let? (check-special 'let))
;; Converts all let special forms in EXPR into equivalent forms using lambda
(define (let-to-lambda expr)
(cond ((atom? expr)
; BEGIN PROBLEM EC
expr
; END PROBLEM EC
)
((quoted? expr)
; BEGIN PROBLEM EC
expr
; END PROBLEM EC
)
((or (lambda? expr)
(define? expr))
(let ((form (car expr))
(params (cadr expr))
(body (cddr expr)))
; BEGIN PROBLEM EC
(cons form (cons params (let-to-lambda body)))
; END PROBLEM EC
))
((let? expr)
(let ((values (cadr expr))
(body (cddr expr)))
; BEGIN PROBLEM EC
(cons (cons 'lambda (cons (car (zip values)) (cons (let-to-lambda (car body)) nil))) (car (cdr (zip values))))
; END PROBLEM EC
))
(else
; BEGIN PROBLEM EC
(map let-to-lambda expr)
; END PROBLEM EC
)))