Parens – ()



Parens – ()

1 0


intro-to-clojure-syntax


On Github rrees / intro-to-clojure-syntax

Parens

()

S-exprs (or lists)

(function arg1 arg2 ... argn)

(1 2 3)
; A number cannot be cast to a function

(str "Hello" " " "World") ; "Hello World"
					

Keywords

:

Superconstants!

(= :a :a) ; true
(:a (hash-map :a 3)) ; 3
((hash-map :a 3) :a) ; 3
	

Def'ing

Linking identities and values

(def i 2)

(defn g [name] (str "Hello " name))
					

Literals

{} [] # `

Collection syntax sugar

{:a 1 :b 7} ; Maps

`(1 2 3) ; Lists

[1 2 3] ; Vectors

#{1 2 3} ; Sets
					

Anonymous functions

#() % fn

;; three ways to write the same thing
#(dec %)
(fn [n] (dec n))
(fn subtract-one [n] (dec n))

(#(dec %) 1) ; 0

((fn [n] (dec n)) 1) ; 0

((fn subtract-one [n] (dec n)) 1) ; 0
					

(map #(dec %) [1 2]) ; (0 1)

(map (fn [n] (dec n)) [1 2]) ; (0 1)

(map (fn subtract-one [n] (dec n)) [1 2]) ; (0 1)
					

Arrows

->>

Threading macros or semantic pipeling

(-> object # to the left
	.setProperty 5
	.toString)

(->> [] # to the right
	cons 1
	cons 2
	str) ; "21"
	

Fear the macro

' ~ ~@

Ah... I got nothing

quote ', unquote ~, unquote-splicing ~@

State

atom @

Functions return the new state

(defn next-step [count] (inc count))
(next-step 3) ; 4
					

Atoms wrap state

(def count (atom 1))
(defn next-step [count] (inc @count))
(next-step 3) ; 4
(deref count) ; 3
					

Bang!

swap!

Persisting state!

(def count (atom 1))
(defn next-step [count] (swap! count inc))
(next-step 3) ; 4
(deref count) ; 4
	

Your turn!

Colon

Semi-colon?

Parens

()

Brackets!

# {} []

Def?

fn #()

' ~ ~@

Arrows

->>

The mighty atom

Bang!

Parens ()