-
Notifications
You must be signed in to change notification settings - Fork 88
/
ch04-concurrency-repl-interactions.clj
1336 lines (1039 loc) · 29.1 KB
/
ch04-concurrency-repl-interactions.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;-----
(def d (delay (println "Running...")
:done!))
;= #'user/d
(deref d)
; Running...
;= :done!
;-----
(def a-fn (fn []
(println "Running...")
:done!))
;= #'user/a-fn
(a-fn)
; Running...
;= :done!
;-----
@d
;= :done!
;-----
(defn get-document
[id]
; ... do some work to retrieve the identified document's metadata ...
{:url "http://www.mozilla.org/about/manifesto.en.html"
:title "The Mozilla Manifesto"
:mime "text/html"
:content (delay (slurp "http://www.mozilla.org/about/manifesto.en.html"))})
;= #'user/get-document
(def d (get-document "some-id"))
;= #'user/d
d
;= {:url "http://www.mozilla.org/about/manifesto.en.html",
;= :title "The Mozilla Manifesto",
;= :mime "text/html",
;= :content #<Delay@2efb541d: :pending>}
;-----
(realized? (:content d))
;= false
@(:content d)
;= "<!DOCTYPE html><html>..."
(realized? (:content d))
;= true
;-----
(def long-calculation (future (apply + (range 1e8))))
;= #'user/long-calculation
;-----
@long-calculation
;= 4999999950000000
;-----
@(future (Thread/sleep 5000) :done!)
;= :done!
;-----
(deref (future (Thread/sleep 5000) :done!)
1000
:impatient!)
;= :impatient!
;-----
(defn get-document
[id]
; ... do some work to retrieve the identified document's metadata ...
{:url "http://www.mozilla.org/about/manifesto.en.html"
:title "The Mozilla Manifesto"
:mime "text/html"
:content (future (slurp "http://www.mozilla.org/about/manifesto.en.html"))})
;-----
(def p (promise))
;= #'user/p
;-----
(realized? p)
;= false
(deliver p 42)
;= #<core$promise$reify__1707@3f0ba812: 42>
(realized? p)
;= true
@p
;= 42
;-----
(def a (promise))
(def b (promise))
(def c (promise))
;-----
(future
(deliver c (+ @a @b))
(println "Delivery complete!"))
;-----
(deliver a 15)
;= #<core$promise$reify__5727@56278e83: 15>
(deliver b 16)
; Delivery complete!
;= #<core$promise$reify__5727@47ef7de4: 16>
@c
;= 31
;-----
(def a (promise))
(def b (promise))
(future (deliver a @b))
(future (deliver b @a))
(realized? a)
;= false
(realized? b)
;= false
(deliver a 42)
;= #<core$promise$reify__5727@6156f1b0: 42>
@a
;= 42
@b
;= 42
;-----
(defn call-service
[arg1 arg2 callback-fn]
; ...perform service call, eventually invoking callback-fn with results...
(future (callback-fn (+ arg1 arg2) (- arg1 arg2))))
;-----
(defn sync-fn
[async-fn]
(fn [& args]
(let [result (promise)]
(apply async-fn (conj (vec args) #(deliver result %&)))
@result)))
((sync-fn call-service) 8 7)
;= (15 1)
;-----
(defn phone-numbers
[string]
(re-seq #"(\d{3})[\.-]?(\d{3})[\.-]?(\d{4})" string))
;= #'user/phone-numbers
(phone-numbers " Sunil: 617.555.2937, Betty: 508.555.2218")
;= (["617.555.2937" "617" "555" "2937"] ["508.555.2218" "508" "555" "2218"])
;-----
(def files (repeat 100
(apply str
(concat (repeat 1000000 \space)
"Sunil: 617.555.2937, Betty: 508.555.2218"))))
;-----
(time (dorun (map phone-numbers files)))
; "Elapsed time: 2460.848 msecs"
;-----
(time (dorun (pmap phone-numbers files)))
; "Elapsed time: 1277.973 msecs"
;-----
(def files (repeat 100000
(apply str
(concat (repeat 1000 \space)
"Sunil: 617.555.2937, Betty: 508.555.2218"))))
(time (dorun (map phone-numbers files)))
; "Elapsed time: 2649.807 msecs"
(time (dorun (pmap phone-numbers files)))
; "Elapsed time: 2772.794 msecs"
;-----
(time (->> files
(partition-all 250)
(pmap (fn [chunk] (doall (map phone-numbers chunk))))
(apply concat)
dorun))
; "Elapsed time: 1465.138 msecs"
;-----
class Person {
public String name;
public int age;
public boolean wearsGlasses;
public Person (String name, int age, boolean wearsGlasses) {
this.name = name;
this.age = age;
this.wearsGlasses = wearsGlasses;
}
}
Person sarah = new Person("Sarah", 25, false);
;-----
(def sarah {:name "Sarah" :age 25 :wears-glasses? false})
;= #'user/sarah
;-----
@(atom 12)
;= 12
@(agent {:c 42})
;= {:c 42}
(map deref [(agent {:c 42}) (atom 12) (ref "http://clojure.org") (var +)])
;= ({:c 42} 12 "http://clojure.org" #<core$_PLUS_ clojure.core$_PLUS_@65297549>)
;-----
(defmacro futures
[n & exprs]
(vec (for [_ (range n)
expr exprs]
`(future ~expr))))
;-----
(defmacro wait-futures
[& args]
`(doseq [f# (futures ~@args)]
@f#))
;-----
(def sarah (atom {:name "Sarah" :age 25 :wears-glasses? false}))
;= #'user/sarah
(swap! sarah update-in [:age] + 3)
;= {:age 28, :wears-glasses? false, :name "Sarah"}
;-----
(swap! sarah (comp #(update-in % [:age] inc)
#(assoc % :wears-glasses? true)))
;= {:age 29, :wears-glasses? true, :name "Sarah"}
;-----
(def xs (atom #{1 2 3}))
;= #'user/xs
(wait-futures 1 (swap! xs (fn [v]
(Thread/sleep 250)
(println "trying 4")
(conj v 4)))
(swap! xs (fn [v]
(Thread/sleep 500)
(println "trying 5")
(conj v 5))))
;= nil
; trying 4
; trying 5
; trying 5
@xs
;= #{1 2 3 4 5}
;-----
(def x (atom 2000))
;= #'user/x
(swap! x #(Thread/sleep %))
;= nil
;-----
(compare-and-set! xs :wrong "new value")
;= false
(compare-and-set! xs @xs "new value")
;= true
@xs
;= "new value"
;-----
(def xs (atom #{1 2}))
;= #'user/xs
(compare-and-set! xs #{1 2} "new value")
;= false
;-----
(reset! xs :y)
;= :y
@xs
;= :y
;-----
(defn echo-watch
[key identity old new]
(println key old "=>" new))
;= #'user/echo-watch
(def sarah (atom {:name "Sarah" :age 25}))
;= #'user/sarah
(add-watch sarah :echo echo-watch)
;= #<Atom@418bbf55: {:name "Sarah", :age 25}>
(swap! sarah update-in [:age] inc)
; :echo {:name Sarah, :age 25} => {:name Sarah, :age 26}
;= {:name "Sarah", :age 26}
(add-watch sarah :echo2 echo-watch)
;= #<Atom@418bbf55: {:name "Sarah", :age 26}>
(swap! sarah update-in [:age] inc)
; :echo {:name Sarah, :age 26} => {:name Sarah, :age 27}
; :echo2 {:name Sarah, :age 26} => {:name Sarah, :age 27}
;= {:name "Sarah", :age 27}
;-----
(remove-watch sarah :echo2)
;= #<Atom@418bbf55: {:name "Sarah", :age 27}>
(swap! sarah update-in [:age] inc)
; :echo {:name Sarah, :age 27} => {:name Sarah, :age 28}
;= {:name "Sarah", :age 28}
;-----
(reset! sarah @sarah)
; :echo {:name Sarah, :age 28} => {:name Sarah, :age 28}
;= {:name "Sarah", :age 28}
;-----
(def history (atom ()))
(defn log->list
[dest-atom key source old new]
(when (not= old new)
(swap! dest-atom conj new)))
(def sarah (atom {:name "Sarah", :age 25}))
;= #'user/sarah
(add-watch sarah :record (partial log->list history))
;= #<Atom@5143f787: {:age 25, :name "Sarah"}>
(swap! sarah update-in [:age] inc)
;= {:age 26, :name "Sarah"}
(swap! sarah update-in [:age] inc)
;= {:age 27, :name "Sarah"}
(swap! sarah identity)
;= {:age 27, :name "Sarah"}
(swap! sarah assoc :wears-glasses? true)
;= {:age 27, :wears-glasses? true, :name "Sarah"}
(swap! sarah update-in [:age] inc)
;= {:age 28, :wears-glasses? true, :name "Sarah"}
(pprint @history)
;= ;= nil
;= ; ({:age 28, :wears-glasses? true, :name "Sarah"}
;= ; {:age 27, :wears-glasses? true, :name "Sarah"}
;= ; {:age 27, :name "Sarah"}
;= ; {:age 26, :name "Sarah"})
;-----
(defn log->db
[db-id identity old new]
(when (not= old new)
(let [db-connection (get-connection db-id)]
...)))
(add-watch sarah "jdbc:postgresql://hostname/some_database" log->db)
;-----
(def n (atom 1 :validator pos?))
;= #'user/n
(swap! n + 500)
;= 501
(swap! n - 1000)
;= #<IllegalStateException java.lang.IllegalStateException: Invalid reference state>
;-----
(def sarah (atom {:name "Sarah" :age 25}))
;= #'user/sarah
(set-validator! sarah :age)
;= nil
(swap! sarah dissoc :age)
;= #<IllegalStateException java.lang.IllegalStateException: Invalid reference state>
;-----
(set-validator! sarah #(or (:age %)
(throw (IllegalStateException. "People must have `:age`s!"))))
;= nil
(swap! sarah dissoc :age)
;= #<IllegalStateException java.lang.IllegalStateException: People must have `:age`s!>
;-----
(defn character
[name & {:as opts}]
(ref (merge {:name name :items #{} :health 500}
opts)))
;-----
(def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50))))
(def bilbo (character "Bilbo" :health 100 :strength 100))
(def gandalf (character "Gandalf" :health 75 :mana 750))
;-----
(defn loot
[from to]
(dosync
(when-let [item (first (:items @from))]
(alter to update-in [:items] conj item)
(alter from update-in [:items] disj item))))
;-----
(wait-futures 1
(while (loot smaug bilbo))
(while (loot smaug gandalf)))
;= nil
@smaug
;= {:name "Smaug", :items #{}, :health 500}
@bilbo
;= {:name "Bilbo", :items #{0 44 36 13 ... 16}, :health 500}
@gandalf
;= {:name "Gandalf", :items #{32 4 26 ... 15}, :health 500}
;-----
(map (comp count :items deref) [bilbo gandalf])
;= (21 29)
(filter (:items @bilbo) (:items @gandalf))
;= ()
;-----
(= (/ (/ 120 3) 4) (/ (/ 120 4) 3))
;= true
;-----
(= ((comp #(/ % 3) #(/ % 4)) 120) ((comp #(/ % 4) #(/ % 3)) 120))
;= true
;-----
(def x (ref 0))
;= #'user/x
;-----
(time (wait-futures 5
(dotimes [_ 1000]
(dosync (alter x + (apply + (range 1000)))))
(dotimes [_ 1000]
(dosync (alter x - (apply + (range 1000)))))))
; "Elapsed time: 1466.621 msecs"
;-----
(time (wait-futures 5
(dotimes [_ 1000]
(dosync (commute x + (apply + (range 1000)))))
(dotimes [_ 1000]
(dosync (commute x - (apply + (range 1000)))))))
; "Elapsed time: 818.41 msecs"
;-----
(defn flawed-loot
[from to]
(dosync
(when-let [item (first (:items @from))]
(commute to update-in [:items] conj item)
(commute from update-in [:items] disj item))))
;-----
(def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50))))
(def bilbo (character "Bilbo" :health 100 :strength 100))
(def gandalf (character "Gandalf" :health 75 :mana 750))
(wait-futures 1
(while (flawed-loot smaug bilbo))
(while (flawed-loot smaug gandalf)))
;= nil
(map (comp count :items deref) [bilbo gandalf])
;= (5 48)
(filter (:items @bilbo) (:items @gandalf))
;= (18 32 1)
;-----
(defn fixed-loot
[from to]
(dosync
(when-let [item (first (:items @from))]
(commute to update-in [:items] conj item)
(alter from update-in [:items] disj item))))
(def smaug (character "Smaug" :health 500 :strength 400 :items (set (range 50))))
(def bilbo (character "Bilbo" :health 100 :strength 100))
(def gandalf (character "Gandalf" :health 75 :mana 750))
(wait-futures 1
(while (fixed-loot smaug bilbo))
(while (fixed-loot smaug gandalf)))
;= nil
(map (comp count :items deref) [bilbo gandalf])
;= (24 26)
(filter (:items @bilbo) (:items @gandalf))
;= ()
;-----
(defn attack
[aggressor target]
(dosync
(let [damage (* (rand 0.1) (:strength @aggressor))]
(commute target update-in [:health] #(max 0 (- % damage))))))
(defn heal
[healer target]
(dosync
(let [aid (* (rand 0.1) (:mana @healer))]
(when (pos? aid)
(commute healer update-in [:mana] - (max 5 (/ aid 5)))
(commute target update-in [:health] + aid)))))
;-----
(def alive? (comp pos? :health))
(defn play
[character action other]
(while (and (alive? @character)
(alive? @other)
(action character other))
(Thread/sleep (rand-int 50))))
;-----
(wait-futures 1
(play bilbo attack smaug)
(play smaug attack bilbo))
;= nil
(map (comp :health deref) [smaug bilbo])
;= (488.80755445030337 -12.0394908759935)
;-----
(dosync
(alter smaug assoc :health 500)
(alter bilbo assoc :health 100))
(wait-futures 1
(play bilbo attack smaug)
(play smaug attack bilbo)
(play gandalf heal bilbo))
;= nil
(map (comp #(select-keys % [:name :health :mana]) deref) [smaug bilbo gandalf])
;= ({:health 0, :name "Smaug"}
;= {:health 853.6622368542827, :name "Bilbo"}
;= {:mana -2.575955687302212, :health 75, :name "Gandalf"})
;-----
(dosync (ref-set bilbo {:name "Bilbo"}))
;= {:name "Bilbo"}
;-----
(dosync (alter bilbo (constantly {:name "Bilbo"})))
; {:name "Bilbo"}
;-----
(defn- enforce-max-health
[{:keys [name health]}]
(fn [character-data]
(or (<= (:health character-data) health)
(throw (IllegalStateException. (str name " is already at max health!"))))))
(defn character
[name & {:as opts}]
(let [cdata (merge {:name name :items #{} :health 500}
opts)
cdata (assoc cdata :max-health (:health cdata))
validators (list* (enforce-max-health name (:health cdata))
(:validators cdata))]
(ref (dissoc cdata :validators)
:validator #(every? (fn [v] (v %)) validators))))
;-----
(def bilbo (character "Bilbo" :health 100 :strength 100))
;= #'user/bilbo
(heal gandalf bilbo)
;= #<IllegalStateException java.lang.IllegalStateException: Bilbo is already at max health!>
;-----
(dosync (alter bilbo assoc-in [:health] 95))
;= {:max-health 100, :strength 100, :name "Bilbo", :items #{}, :health 95, :xp 0}
(heal gandalf bilbo)
;= #<IllegalStateException java.lang.IllegalStateException: Bilbo is already at max health!>
;-----
(defn heal
[healer target]
(dosync
(let [aid (min (* (rand 0.1) (:mana @healer))
(- (:max-health @target) (:health @target)))]
(when (pos? aid)
(commute healer update-in [:mana] - (max 5 (/ aid 5)))
(alter target update-in [:health] + aid)))))
;-----
(dosync (alter bilbo assoc-in [:health] 95))
;= {:max-health 100, :strength 100, :name "Bilbo", :items #{}, :health 95}
(heal gandalf bilbo)
;= {:max-health 100, :strength 100, :name "Bilbo", :items #{}, :health 100}
(heal gandalf bilbo)
;= nil
;-----
(defn unsafe
[]
(io! (println "writing to database...")))
;= #'user/unsafe
(dosync (unsafe))
;= #<IllegalStateException java.lang.IllegalStateException: I/O in transaction>
;-----
(def x (ref (java.util.ArrayList.)))
;= #'user/x
(wait-futures 2 (dosync (dotimes [v 5]
(Thread/sleep (rand-int 50))
(alter x #(doto % (.add v))))))
;= nil
@x
;= #<ArrayList [0, 0, 1, 0, 2, 3, 4, 0, 1, 2, 3, 4]>
;-----
(def x (ref 0))
;= #'user/x
(dosync
@(future (dosync (ref-set x 0)))
(ref-set x 1))
;= #<RuntimeException java.lang.RuntimeException:
;= Transaction failed after reaching retry limit>
@x
;= 0
;-----
(ref-max-history (ref "abc" :min-history 3 :max-history 30))
;= 30
;-----
(def a (ref 0))
(future (dotimes [_ 500] (dosync (Thread/sleep 200) (alter a inc))))
;= #<core$future_call$reify__5684@10957096: :pending>
@(future (dosync (Thread/sleep 1000) @a))
;= 28
(ref-history-count a)
;= 5
;-----
(def a (ref 0))
(future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc))))
;= #<core$future_call$reify__5684@10957096: :pending>
@(future (dosync (Thread/sleep 1000) @a))
;= 500
(ref-history-count a)
;= 10
;-----
(def a (ref 0 :max-history 100))
(future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc))))
;= #<core$future_call$reify__5684@10957096: :pending>
@(future (dosync (Thread/sleep 1000) @a))
;= 500
(ref-history-count a)
;= 10
;-----
(def a (ref 0 :min-history 50 :max-history 100))
(future (dotimes [_ 500] (dosync (Thread/sleep 20) (alter a inc))))
@(future (dosync (Thread/sleep 1000) @a))
;= 33
;-----
(def daylight (ref 1))
(defn attack
[aggressor target]
(dosync
(let [damage (* (rand 0.1) (:strength @aggressor) @daylight)]
(commute target update-in [:health] #(max 0 (- % damage))))))
;-----
map
;= #<core$map clojure.core$map@501d5ebc>
#'map
;= #'clojure.core/map
@#'map
;= #<core$map clojure.core$map@501d5ebc>
;-----
(def ^:private everything 42)
;-----
(def ^{:private true} everything 42)
;-----
(def ^:private everything 42)
;= #'user/everything
(ns other-namespace)
;= nil
(refer 'user)
;= nil
everything
;= #<CompilerException java.lang.RuntimeException:
;= Unable to resolve symbol: everything in this context, compiling:(NO_SOURCE_PATH:0)>
@#'user/everything
;= 42
;-----
(meta #'a)
;= {:ns #<Namespace user>, :name a, :doc "A sample value.", :line 1, :file "NO_SOURCE_PATH"}
;-----
(def ^:const everything 42)
;-----
(def max-value 255)
;= #'user/max-value
(defn valid-value?
[v]
(<= v max-value))
;= #'user/valid-value?
(valid-value? 218)
;= true
(valid-value? 299)
;= false
(def max-value 500)
;= #'user/max-value
(valid-value? 299)
;= true
;-----
(def ^:const max-value 255)
;= #'user/max-value
(defn valid-value?
[v]
(<= v max-value))
;= #'user/valid-value?
(def max-value 500)
;= #'user/max-value
(valid-value? 299)
;= false
;-----
(let [a 1
b 2]
(println (+ a b))
(let [b 3
+ -]
(println (+ a b))))
;= 3
;= -2
;-----
(def ^:dynamic *max-value* 255)
;= #'user/*max-value*
(defn valid-value?
[v]
(<= v *max-value*))
;= #'user/valid-value?
(binding [*max-value* 500]
(valid-value? 299))
;= true
;-----
(binding [*max-value* 500]
(println (valid-value? 299))
(doto (Thread. #(println "in other thread:" (valid-value? 299)))
.start
.join))
;= true
;= in other thread: false
;-----
(def ^:dynamic *var* :root)
;= #'user/*var*
(defn get-*var* [] *var*)
;= #'user/get-*var*
(binding [*var* :a]
(binding [*var* :b]
(binding [*var* :c]
(get-*var*))))
;= :c
;-----
(binding [*var* :a]
(binding [*var* :b]
(binding [*var* :c]
(binding [*var* :d]
(get-*var*)))))
;= :d
;-----
(defn http-get
[url-string]
(let [conn (-> url-string java.net.URL. .openConnection)
response-code (.getResponseCode conn)]
(if (== 404 response-code)
[response-code]
[response-code (-> conn .getInputStream slurp)])))
(http-get "http://google.com/bad-url")
;= [404]
(http-get "http://google.com/")
;= [200 "<!doctype html><html><head>..."]
;-----
(def ^:dynamic *response-code* nil)
(defn http-get
[url-string]
(let [conn (-> url-string java.net.URL. .openConnection)
response-code (.getResponseCode conn)]
(when (thread-bound? #'*response-code*)
(set! *response-code* response-code))
(when (not= 404 response-code) (-> conn .getInputStream slurp))))
(http-get "http://google.com")
;= "<!doctype html><html><head>..."
*response-code*
;= nil
(binding [*response-code* nil]
(let [content (http-get "http://google.com/bad-url")]
(println "Response code was:" *response-code*)
; ... do something with `content` if it is not nil ...
))
;= Response code was: 404
;= nil
;-----
(binding [*max-value* 500]
(println (valid-value? 299))
@(future (valid-value? 299)))
; true
;= true
;-----
(binding [*max-value* 500]
(map valid-value? [299]))
;= (false)
;-----
(map #(binding [*max-value* 500]
(valid-value? %))
[299])
;= (true)
;-----
def foo
x = 123
y = 456
x = x + y
end
;-----
(defn never-do-this []
(def x 123)
(def y 456)
(def x (+ x y)
x))
;-----
(def x 80)
;= #'user/x
(defn never-do-this []
(def x 123)
(def y 456)
(def x (+ x y))
x)
;= #'user/never-do-this
(never-do-this)
;= 579
x
;= 579
;-----
(def x 0)
;= #'user/x
(alter-var-root #'x inc)
;= 1
;-----
(def j)
;= #'user/j
j
;= #<Unbound Unbound: #'user/j>
;-----
(declare complex-helper-fn other-helper-fn)
(defn public-api-function
[arg1 arg2]
...
(other-helper-fn arg1 arg2 (complex-helper-fn arg1 arg2))
(defn- complex-helper-fn
[arg1 arg2]
...)
(defn- other-helper-fn
[arg1 arg2 arg3]
...)
;-----
(def a (agent 500))
;= #'user/a
(send a range 1000)
;= #<Agent@53d2f8be: 500>
@a
;= (500 501 502 503 504 ... 999)
;-----
(def a (agent 0))
;= #'user/a
(send a inc)
;= #<Agent@65f7bb1f: 1>
;-----
(def a (agent 5000))
(def b (agent 10000))
(send-off a #(Thread/sleep %))
;= #<Agent@da7d7b5: 5000>
(send-off b #(Thread/sleep %))