Monday 1 June 2015

# Living clojure - day 1

Living Clojure is an awesome book which, not surprisingly, is about Clojure. Contained within is a training plan designed to get you up and running. The first few weeks are all based around the challenges found on 4clojure.org. I’ve not quite got my head around emacs yet, so I used light table as a scratchpad.

### Intro to Strings

The solution to this one was a straight forward string.

``(= "HELLO WORLD" (.toUpperCase "hello world"))``

### Intro to Lists

Re-enforcing that lists can be made in two ways. One is with the list function and other with the `'` prefix. Lists are good for iterating over and can be infinite, however they suck at accessing by index.

``(= (list :a :b :c) '(:a :b :c))``

### Lists: conj

conj is short for conjoin. It puts items into the start of a list

``````(= '(1 2 3 4) (conj '(2 3 4) 1))
(= '(1 2 3 4) (conj '(3 4) 2 1))

;; I whipped this one up
(conj '(:horse :is :fast) :the)
;; (:the :horse :is :fast)``````

### Intro to Vectors

Vectors are much faster at access by index. They can be made in a few ways, most simply by `[ ]`. I note that most commonly they are used as the means to supply arguments to functions. Turns out they can also be equal to lists. #whoknew

``(= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c))``

### Vectors: conj

`conj` works on vectors also.

``(= [1 2 3 4] (conj [1 2 3] 4))``

### Intro to Sets

Sets are “mathy” things. Useful for intersection, union etc etc. Sets can be created with the `set` function, or can be done with the `#` shortcut.

``````(= (set '(:a :b :c :d)) (set '(:a :a :b :c :c :c :c :d :d)))
(= #{:a :b :c :d} (clojure.set/union #{:a :b :c} #{:b :c :d}))``````

### Sets: conj

`Conj` seems to work on all things “listy” / “collectiony”.

``(= #{1 2 3 4} (conj #{1 4 3} 2))``

### Intro to Maps

Maps are for `key=value` pairings. They can be made using the hash-map keyword, or using plain ol’ braces.

``````(= 20 ((hash-map :a 10, :b 20, :c 30) :b))
(= 20 (:b {:a 10, :b 20, :c 30}))``````

### Maps: conj

Of course, conj works on maps.

``(= {:a 1, :b 2, :c 3} (conj {:a 1} [:b 2] [:c 3]))``

### Intro to sequences

Any type of sequences are can be operated on. Lists and vectors are both types of sequences.

``````(= 3 (first '(3 2 1)))
(= 3 (second [2 3 4]))
(= 3 (last (list 1 2 3)))``````

And that was day one.