Today I started reading through this book to learn some Clojure. It’s called Clojure for the Brave and True.
I thought I would make myself a little cheatsheet that grows as I progress through the book.
Forms
These are like the building blocks of the files.
1
"This string"
["Vectors" "of" "strings" "are" "a" "thing"]
Operators
All operations use the same structure. Given an operator operator
and operands
op1, op2, ... opN
, you use the following structure:
(operator op1 op2 ... opN)
Comments
; This is a single line comment
Control Flow
if
(if some-boolean-form
then-form
an-optional-else form)
If the
else-form
is omitted and triggered, thennil
is returned.The
then-form
andelse-form
can only be a one-liner, seedo
if you need more functionality than that
do
(if some-boolean-form
(do "Some truthy thing 1"
"Some truthy thing 2")
(do "Some falsey thing 1"
"Some falsey thing 2"))
when
- Think of this as an
if-do
without anelse-form
(when some-true-form
(println "True thing found"))
Booleans
true
orfalse
nil
is no value
Some operators:
(or op1 op2 ... opN)
: return first truthy value or last value(and op1 op2 ... opN)
: return the first falsey value or the last truthy value(= op1 op2)
: test for equality(nil? op1)
: check fornil
Save state
(def varName value)
Data Structures
- All data structures are immutable
Numerical Things
- Numbers:
17
- Floats:
3.4
- Ratios:
51/100
Strings
- Denoted by double quotes
- Escape any double quotes inside as needed
Maps
; An empty map
{}
; A map with keywords for keys
{:firstname "Andy"
:lastname "Lu"}
; Mapping a string to a function
{"Totally-legal" +}
; Nested Maps
{:name {:first "Andy" :last "Lu"}}
; Hash Map
(hash-map :firstname "Andy" :lastname "Lu")
Reading from maps
get
:(get {:a 1 :b 2} :b)
, returns2
- ‘
(get {:a 1 :b 2} :c)
, returns `nil’
- ‘get-in’: Used for nested maps
(get-in {:a 0 :b {:c 100}} [:b :c])
, returns100
- Using a map like an operator
({:name "Andy"} :name)
, returns"Andy"
Keywords
- Primarily used as keys in maps
- Denoted
:a
Vectors
- Zero Indexed
- Declaring one:
[3 2 1]
(vector "some" "list" "of" "things")
, returns["some" "list" "of" "things"]
- Adding to the end of a vector:
(conj [1 2 3] 4)
, returns[1 2 3 4]
Lists
- Zero Indexed
- Declaring:
'(1 2 3 4)
, returns(1 2 3 4)
'(list 1 "two" {3 4})
, returns(1 "two" {3 4})
- Retriving the
nth
value:(nth '(4 3 2 1 0) 1)
, returns3
Sets
- Contain only unique values
- Declaring:
#{"word" 20 :name}
, returns#{"word" 20 :name}
(set [1 1 2 3 3 3 4])
, returns#{1 2 3 4}
- Checking for a value in a set:
- If you want a boolean back:
(contains? #{:a :b} :a)
, returnstrue
(contains? #{1 2} 3)
, returnsfalse
- If you want a value back:
(:a #{:a :b :c})
, returns:a
(get #{1 2} 1)
, returns1
(get #{:a nil} nil)
, returnsnil
- If you want a boolean back: