forked from swannodette/lt-cljs-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lt-cljs-tutorial.cljs
1448 lines (905 loc) · 37.4 KB
/
lt-cljs-tutorial.cljs
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
;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
;; An Introduction to ClojureScript for Light Table users
;; +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
;; Basics
;; ============================================================================
;; To begin, open the command pane (type Control-SPACE), Add Connection, select
;; Light Table UI. Once connected you can evaluate all the forms in this file
;; by placing the cursor after the form and typing Command-ENTER.
;; IMPORTANT: You must evaluate the very first form, the namespace
;; definition.
;; Declaring a namespaces
;; ----------------------------------------------------------------------------
;; ClojureScript supports modularity via namespaces. They allow you to group
;; logical definitions together.
(ns lt-cljs-tutorial
(:require [clojure.string :as string]))
;; :require is how you can import functionality from a different namespace into
;; the current one. Here we are requiring `clojure.string` and giving it an
;; alias. We could write the following:
(clojure.string/blank? "")
;; But that's really verbose compared to:
(string/blank? "")
;; Comments
;; ----------------------------------------------------------------------------
;; There are three ways to create comments in ClojureScript. The first way is
;; by preceding a line with a semi-colon, just like the lines you are reading
;; now.
;; The second way is by preceding a form with `#_`. This causes ClojureScript
;; to skip the evaluation of only the form immediately following, without
;; affecting the evaluation of the surrounding forms.
;; Try to reveal the secret message below:
(str "The secret word is " #_(string/reverse "tpircSerujolC"))
;; Finally, you can also create a comment using the `comment` macro. One common
;; technique is to use the `comment` macro to include code to be evaluated in a
;; REPL, but which you do not normally want to be included in the compiled
;; source.
;; For example, try placing your cursor after the last `)` below and type
;; Command-ENTER:
(comment
(string/upper-case "This is only a test...")
)
;; The `comment` macro makes the whole form return `nil`. Now go back and
;; highlight just the middle line, then type Command-ENTER. In this way
;; you can include code samples or quick tests in-line with the rest of
;; your code.
;; Definitions
;; ----------------------------------------------------------------------------
;; Once you have a namespace, you can start creating top level definitions in
;; that namespace.
;; You can define a top level with `def`.
(def x 1)
x
;; You can also refer to top level definitions by fully qualifying them.
lt-cljs-tutorial/x
;; This means top levels can never be shadowed by locals and function
;; parameters.
(let [x 2]
lt-cljs-tutorial/x)
;; One way to define a function is like this.
(def y (fn [] 1))
(y)
;; Defining functions in ClojureScript is common enough that `defn` sugar is
;; provided and idiomatic.
(defn z [] 1)
(z)
;; Literal data types
;; ----------------------------------------------------------------------------
;; ClojureScript comes out of the box with the usual useful data literals.
;; Booleans
(def a-boolean true)
;; Strings
(def a-string "Hello!")
;; Regular Expressions
(def a-regexp #"\d{3}-?\d{3}-?\d{4}")
;; Numbers
(def a-number 1)
;; Function literals
;; ----------------------------------------------------------------------------
;; ClojureScript also supports a shorthand function literal which is useful
;; You can use the % and %N placeholders to represent function arguments.
;; You should not abuse the function literal notation as it degrades readability
;; outside of simple cases. It is nice for simple functional cases such as
;; the following. You could map over a ClojureScript vector like this:
(map (fn [n] (* n 2)) [1 2 3 4 5])
;; Or you can save typing a few characters like this:
(map #(* % 2) [1 2 3 4 5])
;; JavaScript data type literals
;; ----------------------------------------------------------------------------
;; You can construct a JavaScript array with the `array` function.
(def an-array (array 1 2 3))
;; But ClojureScript also supports JavaScript data literals via the `#js`
;; reader literal.
(def another-array #js [1 2 3])
;; Similarly, you can create simple JavaScript objects with `js-obj`.
(def an-object (js-obj "foo" "bar"))
;; But again you can save a few characters with `#js`.
(def another-object #js {"foo" "bar"})
;; It's important to note that `#js` is shallow, the contents of `#js` will be
;; ClojureScript data unless preceded by `#js`.
;; This is a mutable JavaScript object with an immutable ClojureScript vector
;; inside.
(def shallow #js {"foo" [1 2 3]})
;; Constructing a type
;; ----------------------------------------------------------------------------
;; Of course some JavaScript data types you will want to create with a
;; constructor.
;; (js/Date.) is equivalent to new Date().
(def a-date (js/Date.))
(def another-date #inst "2014-01-15")
;; Note the above returns an `#inst` data literal.
(def another-regexp (js/RegExp. "\\d{3}-?\\d{3}-?\\d{4}"))
;; Handy
;; NOTE: js/Foo is how you refer to global JavaScript entities of any kind.
js/Date
js/RegExp
js/requestAnimationFrame
;; If you're curious about other JavaScript interop jump to the bottom of this
;; tutorial.
;; ClojureScript data types
;; ============================================================================
;; Unless there is a good reason, you should generally write your ClojureScript
;; programs with ClojureScript data types. They have many advantages over
;; JavaScript data types - they present a uniform API and they are immutable.
;; Vectors
;; ----------------------------------------------------------------------------
;; Instead of arrays, ClojureScript programmers use persistent vectors. They are
;; like arrays - they support efficient random access, efficient update
;; and efficient addition to the end.
(def a-vector [1 2 3 4 5])
;; We can get the length of a vector in constant time via `count`.
(count a-vector)
;; We can add an element to the end.
(def another-vector (conj a-vector 6))
;; Note this does not mutate the array! `a-vector` will be left
;; unchanged.
a-vector
another-vector
;; Hallelujah! Here is where some ClojureScript magic
;; happens. `another-vector` appears to be a completely new vector
;; compared to `a-vector`. But it is not really so. Internally, the new
;; vector efficiently shares the `a-vector` structure. In this way, you
;; get the benefits of immutability without paying in performance.
;; We can access any element in a vector with `nth`. The following
;; will return the second element.
(nth a-vector 1)
(nth ["foo" "bar" "baz"] 1)
;; Or with `get`...
(get a-vector 0)
;; ...which allows you to return an alternate value when the index is
;; out-of bounds.
(get a-vector -1 :out-of-bounds)
(get a-vector (count a-vector) :out-of-bounds)
;; Surprisingly, vectors can be treated as functions. This is actually
;; a very useful property for associative data structures to have as
;; we'll see below with sets.
(a-vector 1)
(["foo" "bar" "baz"] 1)
;; Maps
;; ----------------------------------------------------------------------------
;; Along with vectors, maps are the most common data type in ClojureScript.
;; Map usage is analogous to the usage of Object in JavaScript, but
;; ClojureScript maps are immutable and considerably more flexible.
;; Let's define a simple map. Note `:foo` is a ClojureScript keyword.
;; ClojureScript programmers prefer to use keywords for keys instead
;; of strings. They are more distinguishable from the rest of the
;; code, more efficient than plain strings, and they can be used in
;; function position (i.e. first position after the open parens), as
;; we'll see in a moment.
(def a-map {:foo "bar" :baz "woz"})
;; We can get the number of key-value pairs in constant time.
(count a-map)
;; We can access a particular value for a key with `get`.
(get a-map :foo)
;; and return an alternative value when the key is not present
(get a-map :bar :not-found)
;; We can add a new key-value pair with `assoc`.
(def another-map (assoc a-map :noz "goz"))
;; Again a-map is unchanged! Same magic as before for vectors
a-map
another-map
;; We can remove a key-value pair with `dissoc`.
(dissoc a-map :foo)
;; Again a-map is unchanged!
a-map
;; Like vectors, maps can act like functions.
(a-map :foo)
;; However ClojureScript keywords themselves can act like functions and the
;; following is more idiomatic.
(:foo a-map)
;; We can check if a map contains a key, with `contains?`.
(contains? a-map :foo)
;; We can get all the keys in a map with `keys`.
(keys a-map)
;; And all of the values with `vals`.
(vals a-map)
;; We can put a lot of things in a map, even other maps
(def a-nested-map {:customer-id 1e6
:preferences {:nickname "Bob"
:avatar "http://en.gravatar.com/userimage/0/0.jpg"}
:services {:alerts {:daily true}}})
;; and navigate its keys to get the nested value you're interested in
(get-in a-nested-map [:preferences :nickname])
(get-in a-nested-map [:services :alerts :daily])
;; or just find a top level key-value pair (i.e. MapEntry) by key
(find a-nested-map :customer-id)
(find a-nested-map :services)
;; There are many cool ways to create maps.
(zipmap [:foo :bar :baz] [1 2 3])
(hash-map :foo 1 :bar 2 :baz 3)
(apply hash-map [:foo 1 :bar 2 :baz 3])
(into {} [[:foo 1] [:bar 2] [:baz 3]])
;; Unlike JavaScript objects, ClojureScript maps support complex keys.
(def complex-map {[1 2] :one-two [3 4] :three-four})
(get complex-map [3 4])
;; Keyword digression
;; ----------------------------------------------------------------------------
;; Let's take a moment to digress about keywords as they are so ubiquitous
;; in ClojureScript code.
(identity :foo)
;; If you add an additional preceding colon you'll get a namespaced keyword.
(identity ::foo)
;; What good is this for? It allows you to put data into collections without
;; fear of namespace clashes without the tedium of manual namespacing them
;; in your source.
(identity {:user/foo ::foo})
;; Namespaced keywords are essential to Light Table's modularity.
;; Sets
;; ----------------------------------------------------------------------------
;; ClojureScript also supports sets.
(def a-set #{:cat :dog :bird})
;; `:cat` is already in `a-set`, so it will be unchanged.
(conj a-set :cat)
;; But `:zebra` isn't.
(conj a-set :zebra)
;; If you haven't guessed already, `conj` is a "polymorphic" function that adds
;; an item to a collection. This is some of the uniformity we alluded to
;; earlier.
;; `contains?` works on sets just like it does on maps.
(contains? a-set :cat)
;; Like vectors and maps, sets can also act as functions. If the argument
;; exists in the set it will be returned, otherwise the set will return nil.
(#{:cat :dog :bird} :cat)
;; This is powerful when combined with conditionals.
(defn check [x]
(if (#{:cat :dog :bird} x)
:valid
:invalid))
(check :cat)
(check :zebra)
;; Lists
;; ----------------------------------------------------------------------------
;; A less common ClojureScript data structure is lists. This may be
;; surprising as ClojureScript is a Lisp, but maps, vectors and sets
;; are the 'go-to' data structures for most applications. Still, lists are sometimes
;; useful—especially when dealing with code (i.e. code is data).
(def a-list '(:foo :bar :baz))
;; `conj` is "polymorphic" on lists as well, and it's smart enough to
;; add the new item in the most efficient way on the basis of the
;; collection type.
(conj a-list :front)
;; and lists are immutable as well
a-list
;; You can get the first element of a list
(first a-list)
;; or the tail of a list
(rest a-list)
;; which allows you to easly verify how ClojureScript shares data
;; structure instead of inefficiently copying data for supporting
;; immutability.
(def another-list (conj a-list :front))
another-list
a-list
(identical? (rest another-list) a-list)
;; `identical?` checks whether two things are represented by the same
;; thing in memory.
;; Equality
;; ============================================================================
;; ClojureScript has a much simpler notion of equality than what is present
;; in JavaScript. In ClojureScript equality is always deep equality.
(= {:foo "bar" :baz "woz"} {:foo "bar" :baz "woz"})
;; Maps are not ordered.
(= {:foo "bar" :baz "woz"} {:baz "woz" :foo "bar"})
;; For sequential collections, equality just works.
(= [1 2 3] '(1 2 3))
;; Again, it is possible to check whether two things are represented
;; by the same thing in memory with `identical?`.
(def my-vec [1 2 3])
(def your-vec [1 2 3])
(identical? my-vec your-vec)
;; Control
;; ============================================================================
;; In order to write useful programs, we need to be able to express
;; control flow. ClojureScript provides the usual control constructs,
;; however truth-y and false-y values are not the same as in
;; JavaScript so it's worth reviewing.
;; if
;; ----------------------------------------------------------------------------
;; 0 is not a false-y value.
(if 0
"Zero is not false-y"
"Yuck")
;; Nor is the empty string.
(if ""
"An empty string is not false-y"
"Yuck")
;; the empty vector
(if []
"An empty vector is not false-y"
"Yuck")
;; the empty list
(if ()
"An empty list is not false-y"
"Yuck")
;; the empty map
(if {}
"An empty map is not false-y"
"Yuck")
;; the empty set
(if #{}
"An empty set is not false-y"
"Yuck")
;; and even the empty regexp
(if #""
"An empty regexp is not false-y"
"Yuck")
;; The only false-y values in ClojureScript are `nil` and `false`. `undefined`
;; is not really a valid ClojureScript value and is generally coerced to `nil`.
;; cond
;; ----------------------------------------------------------------------------
;; Nesting `if` tends to be noisy and hard to read so ClojureScript
;; provides a `cond` macro to deal with this.
(cond
nil "Not going to return this"
false "Nope not going to return this either"
:else "Default case")
;; loop/recur
;; ----------------------------------------------------------------------------
;; The most primitive looping construct in ClojureScript is `loop`/`recur`.
;; Like `let`, `loop` establishes bindings and allows you to set their initial values.
;; Like `let`, you may have a sequence of forms for the body. In tail
;; positions, you may write a `recur` statement that will set the bindings for
;; the next iteration of the `loop`. Using `loop`/`recur` is usually considered bad
;; style if a reasonable functional solution via `map`/`filter`/`reduce` or a list
;; comprehension is possible.
;; While you might write this in JavaScript:
;;
;; var ret = [];
;; for(var i = 0; i < 10; i++) ret.push(i)
;;
;; In ClojureScript you would write `loop`/`recur` like so:
(loop [i 0 ret []]
(if (< i 10)
(recur (inc i) (conj ret i))
ret))
;; Again avoid `loop`/`recur` unless you really need it. The loop above would
;; be better expressed as the following:
(into [] (range 10))
;; Moar functions
;; ============================================================================
;; Functions are the essence of any significant ClojureScript program, so
;; we will dive into features that are unique to ClojureScript functions that
;; might be unfamiliar.
;; Here is a simple function that takes two arguments and adds them.
(defn foo1 [a b]
(+ a b))
(foo1 1 2)
;; Functions can have multiple arities.
(defn foo2
([a b] (+ a b))
([a b c] (* a b c)))
(foo2 3 4)
(foo2 3 4 5)
;; Multiple arities can be used to supply default values.
(defn defaults
([x] (defaults x :default))
([x y] [x y]))
(defaults :explicit)
(defaults :explicit1 :explicit2)
;; Functions support rest arguments.
(defn foo3 [a b & d]
[a b d])
(foo3 1 2)
(foo3 1 2 3 4)
;; You can apply functions.
(apply + [1 2 3 4 5])
;; multimethods
;; ----------------------------------------------------------------------------
;; Often when you need some polymorphism, and performance isn't an issue,
;; multimethods will suffice. Multimethods are functions that allow open
;; extension, but instead of limiting dispatch to type, dispatch is controlled
;; by whatever value the dispatch fn originally supplied to `defmulti` returns.
;; Here is the simplest multimethod you can write. It simply dispatches on
;; the value received.
(defmulti simple-multi identity)
;; Now we can define methods for particular values.
(defmethod simple-multi 1
[value] "Dispatched on 1")
(simple-multi 1)
(defmethod simple-multi "foo"
[value] "Dispatched on foo")
(simple-multi "foo")
;; However we haven't defined a case for "bar"
;; (Highlight and evaluate the `simple-multi` form below)
(comment
(simple-multi "bar")
)
;; Here is a function that takes a list. It dispatches on the first element
;; of the list!
(defmulti parse (fn [[f & r :as form]] f))
(defmethod parse 'if
[form] {:op :if})
(defmethod parse 'let
[form] {:op :let})
(parse '(if a b c))
(parse '(let [x 1] x))
;; Scoping
;; ============================================================================
;; Unlike JavaScript, there is no hoisting in ClojureScript. ClojureScript
;; has lexical scoping.
(def some-x 1)
(let [some-x 2]
some-x)
some-x
;; Closures
;; ----------------------------------------------------------------------------
;; Could a language with such a name miss closures? Surely it can't. You
;; may be already familiar with them in JavaScript, even if it's a
;; variable scoped language.
(let [a 1e3]
(defn foo []
(* a a))
(defn bar []
(+ (foo) a)))
;; Above we defined `foo` and `bar` functions inside the scope of a
;; `let` form and they both know about `a` (i.e. they close over `a`)
;; Note, even if defined inside a `let`, `foo` and `bar` are available
;; in the outer scope. This is because all `def` expressions are always
;; top level. See the footnote at the end of this section.
(foo)
(bar)
;; And Nobody else.
(comment
(defn baz []
(type a))
(baz)
)
;; That's why some people say that closures are the poor man's objects.
;; They encapsulate the information as well.
;; But in ClojureScript, functions' parameters and let bindings' locals
;; are not mutable! That goes for loop locals, too!
(let [fns (loop [i 0 ret []]
(if (< i 10)
(recur (inc i) (conj ret (fn [] i)))
ret))]
(map #(%) fns))
;; In JavaScript you would see a list of ten 9s. In ClojureScript we
;; see the expected numbers from 0 to 9.
;; FOOTNOTE:
;;
;; `def` expressions (including `defn`) are always top level. People familiar
;; with Scheme or other Lisps often mistakenly write the following in Clojure:
(defn not-scheme []
(defn no-no-no []))
;; This is almost always incorrect. If you need to write a local function just
;; do it with a let binding.
(defn outer-fn []
(let [inner-fn (fn [])]))
;; Destructuring
;; ============================================================================
;; In any serious ClojureScript program, there will be significant amounts of
;; data manipulation. Again, we will see that ClojureScript's uniformity
;; pays off.
;; In ClojureScript anywhere bindings are allowed (like `let` or function
;; parameters), destructuring is allowed. This is similar to the destructuring
;; proposed for ES6, but the system provided in ClojureScript benefits from
;; all the collections supporting uniform access.
;; Sequence destructuring
;; ----------------------------------------------------------------------------
;; Destructuring sequential types is particularly useful.
(let [[f & r] '(1 2 3)]
f)
(let [[f & r] '(1 2 3)]
r)
(let [[r g b] [255 255 150]]
g)
;; _ is just a convention for saying that you are not interested at the
;; item in the corresponding position. it has no other special meaning.
;; Here we're only interested at the third local variable named `b`.
(let [[_ _ b] [255 255 150]]
b)
;; destructuring function arguments works just as well. Here we are
;; only intersted at the second argument `g`.
(defn green [[_ g _]] g)
(green [255 255 150])
;; Map destructuring
;; ----------------------------------------------------------------------------
;; Map destructuring is also useful. Here we destructure the value for the
;; `:foo` key and bind it to a local `f`, and the value for `:baz` key
;; and bind it to a local `b`.
(let [{f :foo b :baz} {:foo "bar" :baz "woz"}]
[f b])
;; If we don't want to rename, we can just use `:keys`.
(let [{:keys [first last]} {:first "Bob" :last "Smith"}]
[first last])
;; The above map destructuring form is very useful when you need to
;; define a function with optional, non positional and defaulted
;; arguments.
(defn magic [& {:keys [k g h]
:or {k 1
g 2
h 3}}]
(hash-map :k k
:g g
:h h))
(magic)
(magic :k 10)
(magic :g 100)
(magic :h 1000)
(magic :k 10 :g 100 :h 1000)
(magic :h 1000 :k 10 :g 100)
;; Sequences
;; ============================================================================
;; We said that ClojureScript data structures are to be preferred as they
;; provide a uniform interface. All ClojureScript collections satisfy
;; the ISeqable protocol, which means iteration is uniform
;; (i.e. polymorphic) for all collection types.
;; Map / Filter / Reduce
;; ----------------------------------------------------------------------------
;; ClojureScript supports the same bells and whistles out of the box that you may
;; be familiar with from other functional programming languages or JavaScript
;; libraries such as Underscore.js
(map inc [0 1 2 3 4 5 6 7 8 9])
(filter even? (range 10))
(remove odd? (range 10))
;; ClojureScript's `map` and `filter` operations are lazy. You can stack up
;; operations without getting too concerned about multiple traversals.
(map #(* % %) (filter even? (range 20)))
(reduce + (range 100))
;; List comprehensions
;; ----------------------------------------------------------------------------
;; ClojureScript supports the list comprehensions you might know from various
;; languages. List comprehensions are sometimes more natural or more readable
;; than a chain of `map` and `filter` operations.
(for [x (range 1 10)
y (range 1 10)]
[x y])
(for [x (range 1 10)
y (range 1 10)
:when (and (zero? (rem x y))
(even? (quot x y)))]
[x y])
(for [x (range 1 10)
y (range 1 10)
:let [prod (* x y)]]
[x y prod])
;; Seqable collections
;; ----------------------------------------------------------------------------
;; Most ClojureScript collections can be coerced into sequences.
(seq {:foo "bar" :baz "woz"})
(seq #{:cat :dog :bird})
(seq [1 2 3 4 5])
(seq '(1 2 3 4 5))
;; Many ClojureScript functions will call `seq` on their arguments in order to
;; provide the expected behavior. The following demonstrates that you can
;; uniformly iterate over all the ClojureScript collections!
(first {:foo "bar" :baz "woz"})
(rest {:foo "bar" :baz "woz"})
(first #{:cat :dog :bird})
(rest #{:cat :dog :bird})
(first [1 2 3 4 5])
(rest [1 2 3 4 5])
(first '(1 2 3 4 5))
(rest '(1 2 3 4 5))
;; Metadata
;; ============================================================================
;; All of the ClojureScript standard collections support metadata. Metadata
;; is a useful way to annotate data without affecting equality. The
;; ClojureScript compiler uses this language feature to great effect.
;; You can add metadata to a ClojureScript collection with `with-meta`. The
;; metadata must be a map.
(def plain-data [0 1 2 3 4 5 6 7 8 9])
(def decorated-data (with-meta plain-data {:url "http://lighttable.com"}))
;; Metadata has no effect on equality.
(= plain-data decorated-data)
;; You can access metadata with `meta`.
(meta decorated-data)
;; Error Handling
;; ============================================================================
;; Error handling in ClojureScript is relatively straightforward and more or
;; less similar to what is offered in JavaScript.
;; You can construct an error like this.
(js/Error. "Oops")
;; You can throw an error like this.
;; (Highlight and evaluate the `throw` form below)
(comment
(throw (js/Error. "Oops"))
)
;; You can catch an error like this.
(try
(throw (js/Error. "Oops"))
(catch js/Error e
e))
;; JavaScript unfortunately allows you to throw anything. You can handle
;; this in ClojureScript with the following.
(try
(throw (js/Error. "Oops"))
(catch :default e
e))
;; Catches are optional. You can also use multiple forms to handle different types of errors.
(try
(throw (js/Error. "Oops"))
(catch js/Error e
e)
(catch Error e
e)
(finally
"Cleanup here"))
;; Mutation
;; ============================================================================
;; Atoms
;; ----------------------------------------------------------------------------
;; A little bit of mutability goes a long way. ClojureScript does not offer
;; any traditional mutable data structures, however it does support identities
;; that can evolve over time via `atom`.
(def x (atom 1))
;; You can dereference the value of an atom with `@`.
@x
;; This is equivalent to calling `deref`.