-
Notifications
You must be signed in to change notification settings - Fork 0
/
01-computer-science-and-programming.scm
148 lines (121 loc) · 2.18 KB
/
01-computer-science-and-programming.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
(import (rnrs (6)))
;;; Exercise 1.1
(* 3 4)
;; 12
(* (+ 5 3)
(- 5 3))
;; 16
(/ (+ (* (- 17 14)
5)
6)
7)
;; 3
;;; Exercise 1.2
(define add-tax
(lambda (x)
"Returns the total price of an item with cost X."
(+ x
(* x 5/100))))
(add-tax 1.29) ;; 1.3545
(add-tax 2.40) ;; 2.52
;;; Exercise 1.3
(define f
(lambda (x)
(* x x)))
(define square f)
(f 7) ;; 49
(square 7) ;; 49
(define f
(lambda (x)
(+ x 2)))
(f 7) ;; 9
(square 7) ;; 49
;;; Exercise 1.4
(define candy-temperature
(lambda (temperature elevation)
"Reduces the TEMPERATURE given in ambiguous degrees by 1 for every 500
feet of ELEVATION."
(round (- temperature
(/ elevation 500)))))
(candy-temperature 244 5280) ;; 233
;;; Exercise 1.5
(define tax
(lambda (income)
"Calculates marginal tax rate for the given INCOME."
(if (< income 10000)
0
(* (- income 10000)
20/100))))
(tax 9999) ;; 0
(tax 12500) ;; 500
;;; Exercise 1.6
(define turkey-servings
(lambda (weight)
"Calculates the servings that can be expected from a turkey of the given
WEIGHT."
(if (< weight 12)
(/ weight 3/4)
(/ weight 1/2))))
(turkey-servings 9) ;; 12
(turkey-servings 12) ;; 24
;;; Exercise 1.7
(define add-max
(lambda (base x y)
"Adds the larger of X or Y to the provided BASE."
(+ base
(if (> x y)
x
y))))
(define absolute-value
(lambda (x)
"Returns the absolute value of X."
((if (< x 0)
-
+)
0 x)))
;;; Exercises 1.8 through 1.11 will be handled separately.
;;; Exercise 1.12
(define f
(lambda (x y)
(if (even? x)
7
(* x y))))
(f 1 16) ;; 16
;;; Exercise 1.13
(- (* (* 4 5)
9)
7)
;; 173
;;; Exercise 1.14
(define average-two-numbers
(lambda (x y)
(/ (+ x y)
2)))
(average-two-numbers 20 200) ;; 110
;;; Exercise 1.15
(define foo
(lambda (x y)
(if (< y 1)
(+ x y)
(/ x y))))
(define foo
(lambda (x y)
(if (> y -1)
(+ x y)
(/ x y))))
(define foo
(lambda (x y)
(if (= y 0)
(+ x y)
(/ x y))))
(define foo
(lambda (x y)
(if (even? y)
(+ x y)
(/ x y))))
;;; Exercise 1.16
(define ladder-height
(lambda (ladder-length ladder-distance)
(sqrt (+ (square ladder-length)
(square ladder-distance)))))
(ladder-height 10 6) ;; 11.661903789690601