forked from benizi/clojure-intro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
intro.haml
667 lines (585 loc) · 19.6 KB
/
intro.haml
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
.slide
%h1 Intro to Clojure
.slide
%h2 About Me
%ul
%li
:marked
[Benjamin R. Haskell](http://benizi.com):
Twitter [@benizi](https://twitter.com/benizi),
GitHub [@benizi](https://github.com/benizi)
%li
Day Job:
:marked
[4moms](http://www.4moms.com/)
(almost exclusively Ruby)
%li Worked professionally with Perl, .NET (C#, VB), JavaScript, PHP, Ruby
%li Run through tutorials on Python, Erlang, Haskell
%li
Like tools that require a lot of configuration/practice to "get":
%ul
%li Vim, Zsh, Linux, XMonad
.slide
%h2 Clojure and Me
%ul
%li Interested in Clojure for about a year
%li No production experience
%li I hate virtually all of my Clojure code, despite making it publicly available
%li
:marked
Solved most [4clojure.com](https://www.4clojure.com) problems.
%li
Built some toy apps:
%ul
%li
:marked
[yu2.be](http://yu2.be/)
%ul
%li really simple YouTube® link shortener
%li Running on Heroku
%li
:marked
[these slides](https://github.com/benizi/clojure-intro)
%ul
%li
:marked
[Ring](https://github.com/ring-clojure/ring)/[Compojure](https://github.com/weavejester/compojure) application
%li that parses HAML/Markdown with jRuby
%li
Munges deck.js templates with
:marked
[enlive](https://github.com/cgrand/enlive)
%li Syntax highlighting with CodeRay (in Ruby)
.slide
%h2 Clojure - Selling Points
%ul
%li
Heavy emphasis on immutability
%ul
%li Referential transparency
%li Prevents "action at a distance"
%li
Built-in concurrency constructs
%ul
%li Hard: Locks, mutexes, semaphores
%li Better: Software Transactional Memory, Agents, Atoms, Refs, Vars
%li
A Lisp
%ul
%li Homoiconicity - Code is data
%li Syntactic sugar for non-list data types
%li
On the JVM (Clojure) or Node.JS/browser (ClojureScript)
%ul
%li Very easy to consume libraries
%li Makes deployment easier
%li REPL: Read, Eval, Print, Loop
.slide
%h2 Immutability
%ul
%li
Mutability causes bugs, action at a distance
:rubycode
# Ruby
puts data.inspect # => { vital_data: 1, other: 2 }
def evil_function(param)
param.delete(:vital_data)
end
evil_function(data)
puts data.inspect # => { other: 2 }
%li
"But isn't immutability inefficient?"
%ul
%li Everything is "pass by value"
%li Lots of data copying
.slide
%h2 Immutability in Clojure
%ul
%li
Clojure implementations of most core data structures are clever and elegant (IMO)
%ul
%li Elegant: Structure sharing makes creation of "related" structures efficient
%li Clever: 5-bit indices squashed into 32-bit ints -> O(log<sub>32</sub>(N)) operations
%center
%table
%tbody
%tr
%td
:marked
![tree structure](http://blog.higher-order.net/files/clj/persistenthashmap1.png)
%td
:marked
![path copying](http://blog.higher-order.net/files/clj/persistenthashmap-pathcopy.png)
:marked
Highly recommended reading: [Karl Krukow blog post](http://blog.higher-order.net/2010/08/16/assoc-and-clojures-persistenthashmap-part-ii/)
.slide
%h2 Concurrency
%ul
%li
Divided along two axes
%ul
%li Coordinated vs Uncoordinated
%li Synchronous vs Asynchronous
%li
Four built-in reference types
%ul
%li Coordinated synchronous: refs
%li Uncoordinated synchronous: atoms
%li Uncoordinated asynchronous: agents
%li (vars solve a different problem)
.slide.comment
%h2 Lots? of Irritating Silly Parentheses
:javascriptcode
var blah = function(x,y) {
var z = function(a,b) {
return 2 + 10 * a + 20 * b;
}
return z(x * 10, y * 2);
}
:clojurecode
(defn blah [x y]
(let [z (fn [a b]
(+ 2 (* 10 a) (* 20 b)))]
(z (* x 10) (* y 2)))
.slide
%h2 Clojure
%ul
%li Enough sales...
%li Rest of talk is introduction to Clojure coding
%li
:marked
[Himera](http://himera.herokuapp.com) - online ClojureScript REPL by [@fogus](https://twitter.com/fogus).
Follow along(!).
%li
:marked
[http://himera.herokuapp.com](http://himera.herokuapp.com)
%iframe{:src => "http://himera.herokuapp.com/index.html",
:style => "width: 100%; min-height: 4in",
:scrolling => "no"}
.slide
%h2 Clojure Basics - Data types
:clojurecode
nil ; equivalent to Java null ;; nil
true ;; Booleans
false ; only nil and false are "falsey"
(map class [ ;; Numbers
1 ; => java.lang.Long
1.2 ; => java.lang.Double
1/2 ; => clojure.lang.Ratio
1N ; => clojure.lang.BigInt
1M ; => java.math.BigDecimal
])
(name :stringy) ; => "stringy" ;; Keywords
::resolved ; => :user/resolve
(in-ns 'whatever)
::resolved ; => :whatever/resolve
'some-thing ; => some-thing ;; Symbols
'whatever/thing ; => whatever/thing
.slide
%h2 Clojure Basics - String-like types
:clojurecode
(class "asdf") ; => java.lang.String ;; Strings
;; strings are sequences of characters
(map identity "asdf") ; => (\a \s \d \f)
(first "\n") ; => \newline
(class \newline) ; => java.lang.Character
(def item "yay")
(str "a" item "b") ; => "ayayb" ; str stringifies and joins
#"regular expression" ;; Regular expressions
(class #"regular expressions")
; => java.util.regex.Pattern
; fewer backticks: #"\d" is like "\\d"
(re-seq #"." "asdf")
; => ("a" "s" "d" "f")
(re-find #"sd" "blah asdf blah")
; => "sd"
(re-find #"sd" "blah blah blah")
; => nil
.slide
%h2 Clojure Basics - Collections
:clojurecode
(list 1 2 3) ; => (1 2 3) ;; Lists
'(1 2 3) ; => (1 2 3) ; quote prevents evaluation
[1 2 3] ;; Vectors
(vec '(1 2 3)) ; => [1 2 3]
(vector 1 2 3) ; => [1 2 3]
([1 2 3] 0) ; => 1
{:a 1 :b 2} ;; Maps
(hash-map :a 1 :b 2) ; => {:a 1, :b 2}
(sorted-map :a 1 :b 2) ; => {:a 1, :b 2} ; (key) order retained
({:a 1 :b 2} :a) ; => 1
\#{:a :b :c} ;; Sets
(hash-set :a :b :c) ; => \#{:a :b :c}
(set [:a :b :c]) ; => \#{:a :b :c}
(sorted-set :a :b :c) ; => \#{:a :b :c} ; order retained
.slide
%h2 Clojure Basics - Comments
:clojurecode
;; Several varieties of comments
; line-based
; everything after the semicolon is ignored by the reader
;; function-like
(comment ...) ; => nil
[1 (comment 2) 3] ; => [1 nil 3]
(comment defn somefunction ...) ; most useful for top-level forms
;; Reader macro #_
#_(...) ; form is completely elided
[1 #_2 3] ; => [1 3]
;; #! shell compatibility
#!/usr/bin/clojure ; not usually a thing,
; but would be ignored
.slide.comment
:clojurecode
;; Vars
#'name ; => (var name)
;; Deref
@value ; => (deref value)
;; Metadata
#^{:doc "string"} value ; => (with-meta value {:doc "string"})
.slide
%h2 Clojure Basics - Order of operations
:clojurecode
;; 1. Read - Convert string representation of data structures
(read-string "(1 2 3)") ; => (1 2 3)
;; 2. Macro expansion - Recursively expand macros
(macroexpand '(defn foo [a] (+ 1 a)))
; => (def foo (clojure.core/fn ([a] (+ 1 a))))
;; 3. Evaluation - Most datatypes evaluate to themselves
(eval 1) ; => 1
(eval :keyword) ; => :keyword
(eval [1 2 3]) ; => [1 2 3]
%div.slide
:marked
I'm being hand-wavy. The actual situation is [...more complex](http://blog.fogus.me/2012/03/27/compiling-clojure-to-javascript-pt-3-the-himera-model/),
[especially for ClojureScript](http://blog.fogus.me/2012/04/25/the-clojurescript-compilation-pipeline/)
.slide
%h2 Clojure evaluation - Lists
%ul
%li
Lists are special
:clojurecode
(eval (read-string "(first-item)"))
; => CompilerException ...
; Unable to resolve symbol: first-item
%li First item is resolved to something...
%li
If it's a function:
%ol
%li Evaluate the remaining items
%li Pass them as arguments to the function
:clojurecode
(x (y 1) (z "a"))
; evaluate (y 1)
; evaluate 1 => 1
; call y with 1 => y-result
; evaluate (z "a")
; evaluate "a" => 1
; call z with "a" => z-result
; call x with y-result and z-result => x-result
.slide
%h2 Clojure evaluation - Special Forms
%ul
%li
If it's a special form, evaluate it specially
%ul
%li
%strong def
interns symbol in the current namespace
:clojurecode
(def symbol init?)
Special because it's very low-level
%li
%strong if
evaluates a test and then one of the two branches
:clojurecode
(if test ; test is evaluated first
when-true ; not evaluated if test is false
when-false) ; not evaluated if test is true
Special because parts of the form need to remain unevaluated
.slide
%h2 Clojure evaluation - Special Forms (cont.)
%ul
%li
%strong do
runs the forms it contains, discarding the results except the last
:clojurecode
(do
(println "Yay") ; => prints: Yay
1234) ; => evaluates to 1234
%li
%strong quote
prevents evaluation of its arguments
:clojurecode
(quote (rm-rf "/"))
; => (rm-rf "/")
Special because its arguments are unevaluated
%li
Equivalent to the reader macro:
%strong '
:clojurecode
(= (quote (a b c))
'(a b c))
.slide
%h2 Clojure Basics - Functions on hash maps
:clojurecode
(:a {:a 1 :b 2}) ; => 1 ; keywords are functions
(:a \#{:a :b}) ; => :a
(0 [1 2 3]) ; => ClassCastException ; longs are not
("a" {"a" 1}) ; => ClassCastException ; nor are strings
(get {:a 1 :b 2} :a) ; => 1 ;; get
(get {:a 1 :b 2} :c) ; => nil
(get {:a 1 :b 2} :c :default) ; => :default
(keys {:a 1 :b 2}) ; => (:a :b)
(vals {:a 1 :b 2}) ; => (1 2)
(assoc {:a 1} :b 2) ; => {:a 1 :b 2}
(dissoc {:a 1 :b 2} :b) ; => {:a 1}
.slide
%h2 Clojure Basics - Sequences
:clojurecode
(cons 4 '(1 2 3)) ; => (4 1 2 3) ;; (cons first rest)
(cons 4 [1 2 3]) ; => (4 1 2 3) ; cons[tructs] a new seq
(cons 4 \#{1 2 3}) ; => (4 1 2 3) ; by appending first to the rest
(cons [:b 2] {:a 1}) ; => ([:b 2] [:a 1])
(conj '(1 2 3) 4) ; => (4 1 2 3) ;; (conj coll item)
(conj [1 2 3] 4) ; => [1 2 3 4] ; conj[oins] efficiently
(conj \#{1 2 3} 4) ; => \#{1 2 3 4} ; (usually same concrete type)
(conj {:a 1} [:b 2]) ; => {:b 2, :a 1} ; position depends on concrete type
(into [] 1 2 3 4) ; => [1 2 3 4] ;; (into coll a b c ...)
(into \#{} 1 2 3 4) ; => \#{1 3 2 4} ; conj[oins] the rest of its
(into {} [:a 1] [:b 2]) ; => {:a 1, :b 2} ; arguments into the first
.slide
%h2 Clojure Let, binding forms
:clojurecode
(let [forms] body) ; Evaluate body with local bindings as expressed by [forms]
;; Many binding forms:
name value ; binds value to name
(let [a (+ 1 2 3)]
a) ; => 6
[a b ...] value ; binds a to first element of value
; binds b to second element of value
; ...
(let [[a b] '(x y)]
(prn {:a a :b b})) ; => prints: {:a x, :b y}
.slide
%h2 Clojure Let, binding forms (cont.)
:clojurecode
;; Map-like binding forms
(def req {:request-type :get, :url "/"}) ; for use below
{name :key} ; pulls :key out of a map-like
(let [{x :request-type} req]
x) ; => :get
{:keys [a b c]} ; pull multiple keys at once,
; where key is same as name
(let [{:keys [request-type url]} req]
(str "TYPE: " request-type " for " url))
; => "TYPE: :get for /"
{:keys [...] :as name} ; also assign the whole map-like to name
(let [{:keys [url] :as r} req]
(= r req)) ; => true
.slide
%h2 Lazy sequences
:clojurecode
;; range with no args generates integers starting at 0
(range) ; => returns lazy sequence: (0 1 2 3 4 ...)
(range x) ; => returns 0 to (dec x)
(range x y) ; => returns x to (dec y)
;; take, drop, and nth can limit the laziness
(take 4 (range)) ; => (0 1 2 3)
(drop 5 (range)) ; => lazy sequence: (5 6 7 8 ...)
(drop 5 (take 8 (range))) ; => (5 6 7)
(nth (range) 20) ; => 20
(nth (range) 0) ; => 0
.slide
%h2 Functional programming
:clojurecode
;; Apply a function with a collection as its arguments
(apply + [1 2 3 4]) ; => 10
; same as: (+ 1 2 3 4)
;; Apply a function with successive items of collections in turn
(map f collection)
; => '((f (first collection))
; (f (second collection))
; ...)
(map identity [1 2 3]) ; => (1 2 3) ;; result is list
(map identity '(1 2 3)) ; => (1 2 3)
(map identity \#{1 2 3}) ; => (1 2 3)
(map str [{:a 1} [1 2] \#{:a :b}])
; => ("{:a 1}" "[1 2]" "{:a :b}")
;; multiple collections stop when the shortest ends
(map vector [:a :b :c] (range))
; => ((vector :a 0) (vector :b 1) (vector :c 2))
; => ([:a 0] [:b 1] [:c 2])
.slide
%h2 Functional programming
:clojurecode
;; Fold over a list
(reduce f initial-value? collection)
(reduce + 0 [1 2 3 4])
; => like repeatedly doing: (f value next-value)
; => (+ 0 1) => 1
; => (+ 1 2) => 3
; => (+ 3 3) => 6
; => (+ 6 4) => 10
;; Composition
(comp f g) ; => function that applies g, then f to the result
(comp inc -) ; => function that negates, then increments
((comp inc -) 42) ; => -41
;; Partial application
(partial f other-args...) ; => function that applies f to args and other-args
(def map-inc (partial map inc))
(map-inc [1 2 3 4]) ; => (2 3 4 5)
(def five-adder (partial + 5))
(five-adder 10 20) ; => 35
.slide
%h2 Clojure threading macros
:clojurecode
(-> x form1 form2 ...) ; passes x to form1, result to form2, etc. as first arg
(-> 1 (inc) (* 2) (/ 7)) ; => 4/7
(/ (* (inc 1) 2) 7)
(->> x form1 form2 ...) ; passes x to form1, result to form2, etc. as last arg
(->> [:a :b] (map str) (apply str)) ; => ":a:b"
(apply str (map str [:a :b]))
.slide
%h2 Clojure Basics - Defining functions
:clojurecode
;; defn is a macro, which expands to def of a (fn) form
(defn entry-printer
"This is an example of binding" ; doc-string
[[key val]]
(println key " => " val))
(entry-printer [:a 1])
; => prints:
; :a => 1
(dorun (map entry-printer {:a 1 :b 2}))
; => prints:
; :a => 1
; :b => 2
; => nil
.slide
%h2 Clojure Namespaces
%ul
%li Map of symbols to vars
%li Named like Java packages (reverse domain names)
%li
Example:
:marked
`com.benizi.superlibrary`
:clojurecode
;; ns macro
(ns some.namespace
(:require [clojure.repl :as repl]) ;; loads and aliases
(:require [clojure.repl]) ;; just loads
(:use [clojure.repl]) ; discouraged ;; imports everything
(:require [clojure.repl :refer (doc source)]) ;; import specific vars
(:import [java.lang String]) ;; String is available
...)
.slide.comment
%h2 Clojure Basics - Don't forget immutability
:clojurecode
(def a {:a 1}) ; => #'user/a
(assoc a :b 2) ; => {:a 1 :b 2}
a ; => {:a 1}
.slide
%h2 Clojure evaluation - my experience
%div Some things that have helped me (maybe) understand what's going on
%ul
%li Don't think in "infix": think of (x y z) as "apply x to y and z"
%li
:clojurecode
(+ 1 2 3) ; "apply sum to 1, 2, and 3"
(< 1 2) ; "apply 'in-order' to 1 and 2 ; => true
(< 1 2 3) ; "apply 'in-order' to 1, 2, and 3 ; => true
%li Hard to remember early on when things need to be in a list
%li If you want it to be evaluated, put it in a list
%li If you don't want evaluation, quote it, or use a vector
.slide.comment
%h2 Clojure Basics - Reference types - refs
%ul
%li Provides a wrapper around a normal entity
%li Coordinates access to that entity
%li Access is only available within a transaction
.slide
%h2 Thanks
%ul
%li
Thanks to
%a{:href => "http://catapultpgh.org/"} Catapult PGH
for hosting
%li
:marked
Bruce Adams [@bruceadams](https://twitter.com/bruceadams)
%li
%a{:href => "https://github.com/pittsburghclj"} Pittsburgh.clj GitHub
%li
%a{:href => "https://github.com/pittsburghclj"} These slides
.slide
%h2 More resources
%ul
%li
Good Books
%ul
%li
Excellent introduction, tour of language:
:marked
[Clojure Programming](http://www.clojurebook.com/)
(better than:
:marked
[Programming Clojure](http://pragprog.com/book/shcloj2/programming-clojure)
)
%li
More philosophical "what makes Clojure different/fun"
:marked
[The Joy of Clojure](http://joyofclojure.com/)
%li
Blog posts
%ul
%li
Clojure's PersistentHashMap posts by Karl Krukow:
:marked
[part i](http://blog.higher-order.net/2009/09/08/understanding-clojures-persistenthashmap-deftwice/),
[part ii](http://blog.higher-order.net/2010/08/16/assoc-and-clojures-persistenthashmap-part-ii/)
%li
Talks
%ul
%li
Rich Hickey
:marked
[Are We There Yet?](http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey),
[Simple Made Easy](http://www.infoq.com/presentations/Simple-Made-Easy) *highly recommended*
.slide
%h2 Even more resources
%ul
%li
Web sites for practicing
%ul
%li
Practice problems
:marked
[4clojure](http://www.4clojure.com)
%ul
%li
:marked
user: [benizi](http://www.4clojure.com/user/benizi)
%li current rank: 14/16,325.
%li Quantity. Not quality.
%li
Good for any language, but very math-heavy:
:marked
[Project Euler](http://projecteuler.net/)
%li
Web sites for reference
%ul
%li
Community documentation
:marked
[ClojureDocs](http://clojuredocs.org)
%li
Search over code (really useful for examples)
:marked
[{:get 'clojure}](http://getclojure.org/)
e.g. search for [conj](http://getclojure.org/search?q=conj&num=0)
%li
IRC
%ul
%li
\#clojure on freenode