MIT Scheme Exercises

  1. Making Lists
  2. Defining Functions
  3. Branching
  4. Local Variables
  5. Repetition

Making Lists

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
#lang racket

;Making Lists
;1
(cons "hello" "world")
;2
(cons 0 '())
;3
(cons 1
(cons 10 100))
;4
(cons 1
(cons 10
(cons 100 '())))
;5
(cons #\I
(cons "saw"
(cons 3
(cons "girls" '()))))
;6
(cons "sum of"
(cons '(1 2 3 4)
(cons "is"
(cons 10 '()))))
;6
(car '(1 2 3 4))
(cdr '(1 2 3 4))
;7
(list)
(list 1)
;8
(list '(1 2) '(3 4))
;9
(list 1 '(1 2) '(3))

Defining Functions

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
#lang racket

;Exercise 1
(define add1
(lambda (x)
(+ x 1)))

(define sub1
(lambda (x)
(- x 1)))

;Exercise 2
;1
(define pi (* 4 (atan 1.0)))
(define g 9.8)
(define angle2radian
(lambda (x)
(* (/ x 180) pi)))
;2
(define dismoving
(lambda (v t)
(* (* (cos (angle2radian 90)) v) t)))
;3
(define fligh_duration
(lambda (Vy)
(/ (* 2 Vy) g)))
;4
(define flight_distance
(lambda (v theta)
(*
(fligh_duration (* v (sin (angle2radian theta))))
(* v (cos (angle2radian theta))))))

Branching

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
#lang racket

;Exercise 1
;1
(define abs
(lambda (x)
(if (< 0 x)
x
(* x -1))))
;2
(define reciprocal
(lambda (x)
(if (= 0 x)
#f
(/ 1 x))))
;3
(define toAscii
(lambda (x)
(if
(or (< x 33) (> x 126))
#f
(integer->char x))))

;Exercise 2
;1
(define func1
(lambda (a b c)
(if (and (> a 0) (> b 0) (> c 0))
(* a b c)
c)))
;2
(define func2
(lambda (a b c)
(if (or (< a 0) (< b 0) (< c 0))
(* a b c)
#f)))

;Exercise 3
(define Score2Grade
(lambda (score)
(cond
((>= score 80) 'A)
((<= 60 score 79) 'B)
((<= 40 score 59) 'C)
;((and (>= score 60) (<= score 79)) 'B)
;((and (>= score 40) (<= score 59)) 'C)
((< score 40) 'D))))

;Exercise 4
(define str "hello")
(eq? str str)
(eq? "hello" "hello")

(eqv? 1.0 1.0)
(eqv? 1 1.0)

(equal? (list 1 2 3) (list 2 3 4))

Local Variables

1
2
3
4
5
6
#lang racket

;Exercise
(define (flight_distance v a)
(let ((r (/ (* 4 a (atan 1.0)) 180)))
(/ (* 2 v v (cos r) (sin r)) 9.8)))

Repetition

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
#lang racket

;Exercise1
;1
(define (my_length ls)
(if (null? ls)
0
(+ 1 (my_length (cdr ls)))))
;2
(define (accumulate ls)
(if (null? ls)
0
(+ (car ls) (accumulate (cdr ls)))))
;3
(define (remove ls x)
(if (null? ls)
'()
(let ((h (car ls)))
((if (eqv? x h)
(lambda (y) y)
(lambda (y) (cons h y)))
(remove (cdr ls) x)))))
;4
(define (find ls x)
(find_aux ls x 0))
(define (find_aux ls x i)
(cond
((null? ls) #f)
((eqv? x (car ls)) i)
(else (find_aux x (cdr ls) (+ i 1)))))
script>