This is a study note of the part I: Basics of the book Getting Clojure.
1 Hello Clojure
Some basic examples:
- Use
;for end of line comment; Use;;for a comment in its line. (str 3 "2" "hi")converts its parameters to strings and concatenates them together.(count "string")counts the length of a string.nil,trueandfalseare predfined constants.(println "anything" true false nil): prints parameters separted by a space.- basic math operators/functions take a variable number of arguments.
(/ 8 3)gives8/3, it has a built-in type ofratio.(quot 8 3)to get the quotient.- a commas
,is a white space in Clojure.
Use def to bind an identifier to a value. The identifier is called a symbol in Clojure. Clojure programmers use all-lower-case-kabab-case to name a symbol. The naming rules for symbols are:
- cannot start with a digit or a colon
:. The colon is used for keywords. - cannot inlucde special characters such as parentheses, square brackets, braces,
@and^. - most characters such as
&,|, or-can be used in a symbol name.
2 Vectors and Lists
- a
vectoris an ordered collections of items that can be of different types. - a
vectorliteral is created by putting values inside a pair of brackets or using thevectorfunction. - functions working with vectors:
count,nth,first - a vector can be called like a function with an index parameter.
- the
restreturns asequencerepresented as items in parentheses or[]if a vector only has zero or one item. (conj v item)appends an item and returns a vector.(cons item v)prepends an item and returns a sequence.()is an empty listUse a single quote
'to create non-empty list:'(1, "two", 3.0). The'is used to tell Clojure that this is a list data, not executable code.Use
listfunction to create a list.The functions
count,nth,first,restwork with a list.(conj l item)create a new list by prepending an item to a list(cons item l)also prepends an item.A vector is like an array and a list is implemented as a linked list.
It is easy to prepend items to a list and append items to a vector.
Clojure uses
persistent datato mean the data is immutable and efficient.Programmers mostly use vector except writing code literals.
3 Map and Set
- Map can be called as a funciton, get
nilif the key doesn’t exist or the key’s value isnil. - Use
contains?to check if a key exists. Keywordis a special type whose names follow the same rules as symbols- Keywords are interned strings that are part of the program
- primarily used as keys in maps
- used as a marker/label/flag
- used as states
- call the keyword like a funciton
assocadds elements anddissocremoves elementskeysandvalsreturn keys and values of a mapcount,first,resttreats maps as a collection of two-element vectors.- Use
sorted-mapto have a sorted map. - both map types don’t support
nth. use
,to separate map key-value pairsSets are about membership.
Both set and keyword can be called as a function: return the value or a
nil.Set can have
nilas its elementUses
containsto return atrue/falseof membership
4 Logic
falseandnilarefalsy, everything else istruthy.andandorreturn one truthy or falsy value of their parameters.- Testing functions:
=,not=,>,>=,<,<=. doevaluates multiple express and return the last value.whenevaluate multiple expressions when the condition is truthy, else returnnilcondtakess multiple pairs of expressions, use:elsefor the catch-all.whenmatch a single value.- constants in case expression are not evaluated
- the last catch-all is optional but generate an error if no match
tryevalutes all experssion till the firstcatchthrowraise anclojure.lang.ExceptionInfoexception usingex-infofunciton.
5 More Capable Functions
- multi-arity function implements filling in defaults for different arities.
- use
[& args]for varargs or variadic functions. - you can mix multi-arity with variadic.
multimethodallows you to pick an implementation based on a splitting function. The splitting function can be a custom function, keyword or built-in functions such asclass.- use
loop,recurfor recurssive functions. - add docstring after symbol names in function defintion.
- use
:preand:postto check pre and post-conditions
6 Functional Things
- Functional toolkit:
apply,partial,complement,every-pred. - Function on the fly:
fn. - Function literal:
#(...),%,%1,%2,%3. - In the wild:
update,update-in,assoc-in.
7 Let
letis local binding,defis global and stable binding.letcan have multiple bindings and multiple expressions.if-letandwhen-let
8 Def, Symbols, and Vars
defbinds a symbol to a value- The
defbinding is stable and global. it is part of the environment. - Symbols are values. Evaluating a symbol gets the bound value. Use
'nameto get a symbol even it is not used in adef. - A
varis a binding ofdefthat is accessed by#'symbol-name. It have methods such as.get,.sym. - Use
(def ^:dynamic *dynamic-symbol* value)to define a dynamic var. - Use
binding [*symbol* value]to change it in a scope. - Use
set!to change a dynamic var from inside a binding. - In the wild:
*print-length*,*1,*2,*3,*e.
9 Namespaces
- When boot up, the current namespace is
user. (ns name)create and set current namespace.- A fully-qualified symbol has a namespace.
- Use
require 'namesapceor:require namespaceto load a namespaace - Use
:asto define alias.:referpulls vars.:refer :allpulls all vars. - By convention, a namespace maps a file path.
.is a folder and-is_. *ns*returns current namespace.ns-map 'namelist all vars;find-ns 'nameget a namespace.namespaceget the namespace of a symbol.- Keywords have a namespace.
- Namespace doesn’t have a hierarchy.
- Namespace loads once. uses
:reloadto reload. Usedefonceto enforce load once.