-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch2.scratch.clj
308 lines (235 loc) · 8.22 KB
/
ch2.scratch.clj
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
;If the core sequence functions first, rest, and cons work on a data structure,
;you can say the data structure implements the sequence abstraction.
;Lists, vectors, sets, and maps all implement the sequence abstraction,
;so they all work with map, as shown here:
(defn titleize
[topic]
(str topic " for the Brave and True"))
(map titleize ["Hamsters" "Ragnarok"])
; => ("Hamsters for the Brave and True" "Ragnarok for the Brave and True")
(map titleize '("Empathy" "Decorating"))
; => ("Empathy for the Brave and True" "Decorating for the Brave and True")
(map titleize #{"Elbows" "Soap Carving"})
; => ("Elbows for the Brave and True" "Soap Carving for the Brave and True")
(map #(titleize (second %)) {:uncomfortable-thing "Winking"})
; => ("Winking for the Brave and True")
(seq '(1 2 3))
; => (1 2 3)
(seq [1 2 3])
; => (1 2 3)
(seq #{1 2 3})
; => (1 2 3)
(seq {:name "Bill Compton" :occupation "Dead mopey guy"})
; => ([:name "Bill Compton"] [:occupation "Dead mopey guy"])
(into {} (seq {:a 1 :b 2 :c 3}))
; => {:a 1, :c 3, :b 2}
(map str ["a" "b" "c"] ["A" "B" "C"])
; => ("aA" "bB" "cC")
(def human-consumption [8.1 7.3 6.6 5.0])
(def critter-consumption [0.0 0.2 0.3 1.1])
(defn unify-diet-data
[human critter]
{:human human
:critter critter})
(map unify-diet-data human-consumption critter-consumption)
; => ({:human 8.1, :critter 0.0}
{:human 7.3, :critter 0.2}
{:human 6.6, :critter 0.3}
{:human 5.0, :critter 1.1})
(def sum #(reduce + %))
(def avg #(/ (sum %) (count %)))
(defn stats
[numbers]
(map #(% numbers) [sum count avg]))
(stats [3 4 10])
; => (17 3 17/3)
(stats [80 1 44 13 6])
; => (144 5 144/5)
(def identities
[{:alias "Batman" :real "Bruce Wayne"}
{:alias "Spider-Man" :real "Peter Parker"}
{:alias "Santa" :real "Your mom"}
{:alias "Easter Bunny" :real "Your dad"}])
(map :real identities)
; => ("Bruce Wayne" "Peter Parker" "Your mom" "Your dad")
(reduce (fn [new-map [key val]]
(assoc new-map key (inc val)))
{}
{:max 30 :min 10})
; => {:max 31, :min 11}
(assoc (assoc {} :max (inc 30))
:min (inc 10))
(assoc {:a 1} :b 2)
; => {:a 1, :b 2}
(assoc {:a 1} :a 2)
; => {:a 2}
(reduce (fn [new-map [key val]]
(if (> val 4)
(assoc new-map key val)
new-map))
{}
{:human 4.1
:critter 3.9})
; => {:human 4.1}
(take 3 [1 2 3 4 5 6 7 8 9 10])
; => (1 2 3)
(drop 3 [1 2 3 4 5 6 7 8 9 10])
; => (4 5 6 7 8 9 10)
(def food-journal
[{:month 1 :day 1 :human 5.3 :critter 2.3}
{:month 1 :day 2 :human 5.1 :critter 2.0}
{:month 2 :day 1 :human 4.9 :critter 2.1}
{:month 2 :day 2 :human 5.0 :critter 2.5}
{:month 3 :day 1 :human 4.2 :critter 3.3}
{:month 3 :day 2 :human 4.0 :critter 3.8}
{:month 4 :day 1 :human 3.7 :critter 3.9}
{:month 4 :day 2 :human 3.7 :critter 3.6}])
(take-while (fn ([x] (< (:month x) 3))) food-journal)
;=>
;({:month 1, :day 1, :human 5.3, :critter 2.3}
; {:month 1, :day 2, :human 5.1, :critter 2.0}
; {:month 2, :day 1, :human 4.9, :critter 2.1}
; {:month 2, :day 2, :human 5.0, :critter 2.5})
({:month 1, :day 1, :human 5.3, :critter 2.3} :month)
;=> 1
(get {:month 1, :day 1, :human 5.3, :critter 2.3} :month)
;=> 1
(drop-while #(< (:month %) 3) food-journal)
; => ({:month 3 :day 1 :human 4.2 :critter 3.3}
;{:month 3 :day 2 :human 4.0 :critter 3.8}
;{:month 4 :day 1 :human 3.7 :critter 3.9}
;{:month 4 :day 2 :human 3.7 :critter 3.6})
(take-while #(< (:month %) 4)
(drop-while #(< (:month %) 2) food-journal))
; => ({:month 2 :day 1 :human 4.9 :critter 2.1}
;{:month 2 :day 2 :human 5.0 :critter 2.5}
;{:month 3 :day 1 :human 4.2 :critter 3.3}
;{:month 3 :day 2 :human 4.0 :critter 3.8})
(filter #(< (:human %) 5) food-journal)
; => ({:month 2 :day 1 :human 4.9 :critter 2.1}
;{:month 3 :day 1 :human 4.2 :critter 3.3}
;{:month 3 :day 2 :human 4.0 :critter 3.8}
;{:month 4 :day 1 :human 3.7 :critter 3.9}
;{:month 4 :day 2 :human 3.7 :critter 3.6})
(filter #(< (:month %) 3) food-journal)
; => ({:month 1 :day 1 :human 5.3 :critter 2.3}
;{:month 1 :day 2 :human 5.1 :critter 2.0}
;{:month 2 :day 1 :human 4.9 :critter 2.1}
;{:month 2 :day 2 :human 5.0 :critter 2.5})
(some #(> (:critter %) 5) food-journal)
; => nil
(some #(> (:critter %) 3) food-journal)
; => true
(some #(and (> (:critter %) 3) %) food-journal)
; => {:month 3 :day 1 :human 4.2 :critter 3.3}
;You can sort elements in ascending order with sort
(sort [3 1 2])
; => (1 2 3)
;sort-by, which allows you to apply a function (sometimes called a key function)
; to the elements of a sequence and use the values it returns to determine the sort order.
(sort-by count ["aaa" "c" "bb"])
; => ("c" "bb" "aaa")
;concat simply appends the members of one sequence to the end of another:
(concat [1 2] [3 4])
; => (1 2 3 4)
;Lazy Seqs
; A lazy seq is a seq whose members aren’t computed until you try to access them.
(def vampire-database
{0 {:makes-blood-puns? false, :has-pulse? true :name "McFishwich"}
1 {:makes-blood-puns? false, :has-pulse? true :name "McMackson"}
2 {:makes-blood-puns? true, :has-pulse? false :name "Damon Salvatore"}
3 {:makes-blood-puns? true, :has-pulse? true :name "Mickey Mouse"}})
(defn vampire-related-details
[social-security-number]
(Thread/sleep 1000)
(get vampire-database social-security-number))
(defn vampire?
[record]
(and (:makes-blood-puns? record)
(not (:has-pulse? record))
record))
(defn identify-vampire
[social-security-numbers]
(first (filter vampire?
(map vampire-related-details social-security-numbers))))
; Infinite Sequences
(concat (take 8 (repeat "na")) ["Batman!"])
; => ("na" "na" "na" "na" "na" "na" "na" "na" "Batman!")
(take 3 (repeatedly (fn [] (rand-int 10))))
; The Collection Abstraction
(empty? [])
; => true
(empty? ["no!"])
; => false
(map identity {:sunlight-reaction "Glitter!"})
; => ([:sunlight-reaction "Glitter!"])
(into {} (map identity {:sunlight-reaction "Glitter!"}))
; => {:sunlight-reaction "Glitter!"}
(map identity [:garlic-clove :garlic-clove])
; => (:garlic-clove :garlic-clove)
(into #{} (map identity [:garlic-clove :garlic-clove]))
; => #{:garlic-clove}
(into {:favorite-emotion "gloomy"} [[:sunlight-reaction "Glitter!"]])
; => {:favorite-emotion "gloomy" :sunlight-reaction "Glitter!"}
(into ["cherry"] '("pine" "spruce"))
; => ["cherry" "pine" "spruce"]
;conj also adds elements to a collection, but it does it in a slightly different way:
(conj [0] [1])
; => [0 [1]]
(conj [0] 1)
; => [0 1]
(conj [0] 1 2 3 4)
; => [0 1 2 3 4]
(conj {:time "midnight"} [:place "ye olde cemetarium"])
; => {:place "ye olde cemetarium" :time "midnight"}
;Function Functions
;apply explodes a seqable data structure so it can be passed to a function that expects a rest parameter.
(max 0 1 2)
; => 2
max [0 1 2])
; => [0 1 2]
; This doesn’t return the greatest element in the vector because max
; returns the greatest of all the arguments passed to it,
(apply max [0 1 2])
; => 2
;it’s as if you called (max 0 1 2)
;partial takes a function and any number of arguments.
; It then returns a new function. When you call the returned function,
; it calls the original function with the original arguments you supplied
; it along with the new arguments.
(def add10 (partial + 10))
(add10 3)
; => 13
(add10 5)
; => 15
(def add-missing-elements
(partial conj ["water" "earth" "air"]))
(add-missing-elements "unobtainium" "adamantium")
; => ["water" "earth" "air" "unobtainium" "adamantium"]
(defn my-partial
[partialized-fn & args]
(fn [& more-args]
(apply partialized-fn (into args more-args))))
(def add20 (my-partial + 20))
(add20 3)
(defn lousy-logger
[log-level message]
(condp = log-level
:warn (clojure.string/lower-case message)
:emergency (clojure.string/upper-case message)))
(def warn (partial lousy-logger :warn))
(warn "Red light ahead")
; => "red light ahead"
;complement
(def not-vampire? (complement vampire?))
; String to Int
(defn str->int
[str]
(Integer. str))
(defn parse
"Convert a CSV into rows of columns"
[string]
(map #(clojure.string/split % #",")
(clojure.string/split string #"\\n")))
(parse "\"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\"")
;=> (["\"Edward Cullen" "10"] ["Bella Swan" "0"] ["Charlie Swan" "0"] ["Jacob Black" "3"] ["Carlisle Cullen" "6\""])