0% found this document useful (0 votes)
191 views2 pages

Cheatsheet Usletter Color

Clojure Cheat Sheet provides concise summaries of Clojure concepts and functions in 3 sentences or less, including: Primitives like numbers, strings, and collections; common functions for creating, examining, and changing collections like vectors, sets and maps; sequences and lazy sequences; transducers; multimethods and protocols; and input/output functions. Special characters and constructs in Clojure are also summarized concisely, such as threading macros, syntax quoting, and reader conditionals.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
191 views2 pages

Cheatsheet Usletter Color

Clojure Cheat Sheet provides concise summaries of Clojure concepts and functions in 3 sentences or less, including: Primitives like numbers, strings, and collections; common functions for creating, examining, and changing collections like vectors, sets and maps; sequences and lazy sequences; transducers; multimethods and protocols; and input/output functions. Special characters and constructs in Clojure are also summarized concisely, such as threading macros, syntax quoting, and reader conditionals.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Clojure Cheat Sheet (Clojure 1.5 - 1.

8, sheet v35)
Documentation
clojure.repl/

doc find-doc apropos dir source pst javadoc (foo.bar/ is


namespace for later syms)

Relations (set of maps, each with same keys, aka rels)


Rel algebra
(clojure.set/) join select project union difference intersection
index rename

Primitives
Numbers
Literals
Arithmetic
Compare
Bitwise

Cast
Test
Random
BigDecimal
Unchecked
Strings
Create
Use
Regex

Letters
Trim
Test

Queues (conj at end, peek & pop from beginning)


Create
clojure.lang.PersistentQueue/EMPTY (no literal syntax or
constructor fn)
Examine
peek
Change
conj pop

Long: 7, hex 0xff, oct 017, base 2 2r1011, base 36 36rCRAZY


BigInt: 7N Ratio: -22/7 Double: 2.78 -1.2e-5 BigDecimal: 4.2M
+ - * / quot rem mod inc dec max min + - * inc dec
== < > <= >= compare
bit-and bit-or bit-xor bit-not bit-flip bit-set bit-shift-right
bit-shift-left bit-and-not bit-clear bit-test (1.6)
unsigned-bit-shift-right (see BigInteger for integers larger
than Long)
byte short int long float double bigdec bigint num rationalize
biginteger
zero? pos? neg? even? odd? number? rational? integer? ratio?
decimal? float?
rand rand-int
with-precision
*unchecked-math* unchecked-add unchecked-dec unchecked-inc
unchecked-multiply unchecked-negate unchecked-subtract

Transients (clojure.org/reference/transients)
Create
transient persistent!
Change
conj! pop! assoc! dissoc! disj! Note: always use return value for later
changes, never original!
Misc
Compare
Test

= identical? not= not compare clojure.data/diff


true? false? instance? nil? (1.6) some?

Sequences
Creating a Lazy Seq
From collection
From producer fn
From constant
From other
From seq

str format "a string" "escapes \b\f\n\t\r\" octal \377 hex \ucafe"
See also section IO/to string
count get subs compare (clojure.string/) join escape split split-lines
replace replace-first reverse (1.8) index-of last-index-of
#"pattern" re-find re-seq re-matches re-pattern re-matcher re-groups
(clojure.string/) replace replace-first re-quote-replacement Note: \
in #"" is not escape char. (re-pattern "\\s*\\d+") can be written
#"\s*\d+"
(clojure.string/) capitalize lower-case upper-case
(clojure.string/) trim trim-newline triml trimr
string? (clojure.string/) blank? (1.8) starts-with? ends-with?
includes?

Other
Characters
Keywords
Symbols
Misc

char char? char-name-string char-escape-string literals: \a


\newline (more at link)
keyword keyword? find-keyword literals: :kw :my.ns/kw ::in-cur-ns
symbol symbol? gensym literals: my-sym my.ns/foo
literals: true false nil

Collections
Collections
Generic ops

Content tests
Capabilities
Type tests

count empty not-empty into conj (clojure.walk/) walk prewalk


prewalk-demo prewalk-replace postwalk postwalk-demo
postwalk-replace
distinct? empty? every? not-every? some not-any?
sequential? associative? sorted? counted? reversible?
coll? list? vector? set? map? seq? (1.6) record? (1.8)
map-entry?

Vectors (conj, pop, & peek at end)


Create
[] vector vec vector-of mapv filterv (clojure.core.rrb-vector/) vector
vec vector-of
Examine
(my-vec idx) ( nth my-vec idx) get peek .indexOf .lastIndexOf
Change
assoc assoc-in pop subvec replace conj rseq update-in (1.7) update
Ops
reduce-kv

Examine
Change
Set ops
Test
Sorted sets
Maps
Create unsorted
Create sorted

Examine
Change

Ops
Entry
Sorted maps

distinct filter remove take-nth for


cons conj concat lazy-cat mapcat cycle interleave interpose
rest nthrest next fnext nnext drop drop-while take-last for
take take-while butlast drop-last for
conj concat distinct flatten group-by partition partition-all
partition-by split-at split-with filter remove replace shuffle
reverse sort sort-by compare
map pmap map-indexed mapcat for replace seque

Rearrange
Process items
Using a Seq
Extract item

first second last rest next ffirst nfirst fnext nnext nth
nthnext rand-nth when-first max-key min-key
zipmap into reduce reductions set vec into-array to-array-2d
mapv filterv
apply
some filter
doseq dorun doall (1.7) run!
realized?

Construct coll
Pass to fn
Search
Force evaluation
Check for forced

Transducers (clojure.org/reference/transducers)

Lists (conj, pop, & peek at beginning)


Create
() list list*
Examine
first nth peek .indexOf .lastIndexOf
Change
cons conj rest pop

Sets
Create unsorted
Create sorted

Seq in, Seq out


Get shorter
Get longer
Tail-items
Head-items
Change

seq vals keys rseq subseq rsubseq sequence


lazy-seq repeatedly iterate
repeat range
file-seq line-seq resultset-seq re-seq tree-seq xml-seq
iterator-seq enumeration-seq
keep keep-indexed

O the shelf

Create your own


Use
Early termination

map mapcat filter remove take take-while take-nth drop


drop-while replace partition-by partition-all keep
keep-indexed map-indexed distinct interpose (1.7) cat
dedupe random-sample
(1.7) completing ensure-reduced unreduced See also section Concurrency/Volatiles
into sequence (1.7) transduce eduction
reduced reduced? deref

Zippers (clojure.zip/)
Create
zipper seq-zip vector-zip xml-zip
Get loc
up down left right leftmost rightmost
Get seq
lefts rights path children
Change
make-node replace edit insert-child insert-left insert-right
append-child remove
Move
next prev
Misc
root node branch? end?

IO
#{} set hash-set
sorted-set sorted-set-by (clojure.data.avl/) sorted-set
sorted-set-by (flatland.ordered.set/) ordered-set (clojure.data.intmap/) int-set dense-int-set
(my-set item) ( get my-set item) contains?
conj disj
(clojure.set/) union difference intersection select See also section Relations
(clojure.set/) subset? superset?
rseq subseq rsubseq

to/from
...
to *out*
to writer

{} hash-map array-map zipmap bean frequencies group-by (clojure.set/) index


sorted-map sorted-map-by (clojure.data.avl/) sorted-map
sorted-map-by (flatland.ordered.map/) ordered-map
(clojure.data.priority-map/) priority-map (flatland.useful.map/)
ordering-map (clojure.data.int-map/) int-map
(my-map k) ( get my-map k) also (:key my-map) ( get
my-map :key) get-in contains? find keys vals
assoc assoc-in dissoc merge merge-with select-keys update-in
(1.7) update (clojure.set/) rename-keys map-invert GitHub:
Medley
reduce-kv
key val
rseq subseq rsubseq

Binary

spit slurp (to writer/from reader, Socket, string with file name, URI, etc.)

to string
from *in*
from reader
from string
Open

Misc

Data readers

pr prn print printf println newline (clojure.pprint/) print-table


(clojure.pprint/) pprint cl-format also: (binding [*out* writer]
...)
format with-out-str pr-str prn-str print-str println-str
read-line (clojure.tools.reader.edn/) read
line-seq (clojure.tools.reader.edn/) read also: (binding [*in*
reader] ...) java.io.Reader
with-in-str (clojure.tools.reader.edn/) read-string
with-open (clojure.java.io/) text: reader writer binary: input-stream
output-stream
(.write ostream byte-arr) (.read istream byte-arr)
java.io.OutputStream java.io.InputStream GitHub: gloss
byte-spec
flush (.close s) file-seq *in* *out* *err* (clojure.java.io/)
file copy delete-file resource as-file as-url as-relative-path
GitHub: fs
*data-readers* default-data-readers *default-data-reader-fn*

Functions
Create
Call
Test

fn defn defn- definline identity constantly memfn comp complement


partial juxt memoize fnil every-pred some-fn
apply -> ->> trampoline as-> cond-> cond->> some-> some->>
fn? ifn?

Abstractions (Clojure type selection flowchart)


Protocols (clojure.org/reference/protocols)
Define
( defprotocol Slicey (slice [at]))
Extend
( extend-type String Slicey (slice [at] ...))
Extend null
( extend-type nil Slicey (slice [_] nil))
Reify
( reify Slicey (slice [at] ...))
Test
satisfies? extends?
Other
extend extend-protocol extenders
Records (clojure.org/reference/datatypes)
Define
( defrecord Pair [h t])
Access
(:h (Pair. 1 2)) 1
Create
Pair. ->Pair map->Pair
Test
record?
Types (clojure.org/reference/datatypes)
Define
( deftype Pair [h t])
Access
(.h (Pair. 1 2)) 1
Create
Pair. ->Pair
( deftype Pair [h t]
Object
With methods
(toString [this] (str "<" h "," t ">")))
Multimethods (clojure.org/reference/multimethods)
Define
( defmulti my-mm dispatch-fn)
Method define
( defmethod my-mm :dispatch-value [args] ...)
Dispatch
get-method methods
Remove
remove-method remove-all-methods
Prefer
prefer-method prefers
Relation
derive underive isa? parents ancestors descendants
make-hierarchy

Loop
Arrange
Scope
Lazy
Doc.

defmacro definline
macroexpand-1 macroexpand (clojure.walk/) macroexpand-all
and or when when-not when-let when-first if-not if-let cond condp
case (1.6) when-some if-some
for doseq dotimes while
.. doto -> ->> as-> cond-> cond->> some-> some->>
binding locking time with-in-str with-local-vars with-open
with-out-str with-precision with-redefs with-redefs-fn
lazy-cat lazy-seq delay
assert comment doc

Special Characters (clojure.org/reference/reader, tutorial)


,

/
\
:
;

*foo*
@

foo#
~
~@
->
->>
(
[
{
#
#"
#{
#(
%
#?
#?@

#foo
$
foo?
foo!
_
#_

Comma reads as white space. Often used between map key/value pairs for readability.
quote: form ( quote form)
Namespace separator (see Primitives/Other section)
Character literal (see Primitives/Other section)
Keyword (see Primitives/Other section)
Single line comment
Metadata (see Metadata section)
earmuffs - convention to indicate dynamic vars, compiler warns if
not dynamic
Deref: @form ( deref form)
Syntax-quote
auto-gensym, consistently replaced with same auto-generated symbol
everywhere inside same ( ... )
Unquote
Unquote-splicing
thread first macro ->
thread last macro ->>
List literal (see Collections/Lists section)
Vector literal (see Collections/Vectors section)
Map literal (see Collections/Maps section)
Var-quote #x ( var x)
#"p" reads as regex pattern p (see Strings/Regex section)
Set literal (see Collections/Sets section)
Anonymous function literal: #(...) (fn [args] (...))
Anonymous function argument: %N is value of anonymous function arg N.
% short for %1. %& for rest args.
(1.7) Reader conditional: #?(:clj x :cljs y) reads as x on JVM, y in
ClojureScript, nothing elsewhere. Other keys: :cljr :default
(1.7) Splicing reader conditional: [1 #?@(:clj [x y] :cljs [w z])
3] reads as [1 x y 3] on JVM, [1 w z 3] in ClojureScript, [1 3]
elsewhere.
tagged literal e.g. #inst #uuid
JavaContainerClass$InnerClass
conventional ending for a predicate, e.g.: zero? vector? instance?
(unenforced)
conventional ending for an unsafe operation, e.g.: set! swap!
alter-meta! (unenforced)
conventional name for an unused value (unenforced)
Ignore next form

Metadata (clojure.org/reference/reader, special_forms)


General
Abbrevs
Common
Examples
On Vars

def if do let letfn quote var fn loop recur set! throw try monitor-enter
monitor-exit
Binding Forms /
(examples) let fn defn defmacro loop for doseq if-let
Destructuring
when-let (1.6) if-some when-some

Vars and global environment (clojure.org/reference/vars)


Def variants
Interned vars
Var objects
Var validators

{:key1 val1 :key2 val2 ...}


Type {:tag Type}, :key {:key true}
:dynamic :private :doc :const
(defn :private String my-fn ...)
(def :dynamic *dyn-var*
val)
meta with-meta vary-meta alter-meta! reset-meta! doc find-doc test

def defn defn- definline defmacro defmethod defmulti defonce


defrecord
declare intern binding find-var var
with-local-vars var-get var-set alter-var-root var? bound?
thread-bound?
set-validator! get-validator

Namespace
Current
Create/Switch
Add
Find
Examine
From symbol
Remove

*ns*
(tutorial) ns in-ns create-ns
alias def import intern refer
all-ns find-ns
ns-name ns-aliases ns-map ns-interns ns-publics ns-refers
ns-imports
resolve ns-resolve namespace the-ns
ns-unalias ns-unmap remove-ns

Loading
Load libs
List loaded
Load misc

(tutorial) require use import refer


loaded-libs
load load-file load-reader load-string

Concurrency
Atoms
Futures

Macros
Create
Debug
Branch

Special Forms (clojure.org/reference/special_forms)

Threads
Volatiles
Misc

atom swap! reset! compare-and-set!


future future-call future-done? future-cancel future-cancelled?
future?
bound-fn bound-fn* get-thread-bindings push-thread-bindings
pop-thread-bindings thread-bound?
(1.7) volatile! vreset! vswap! volatile?
locking pcalls pvalues pmap seque promise deliver

Refs and Transactions (clojure.org/reference/refs)


Create
ref
Examine
deref @ (@form (deref form))
Transaction
sync dosync io!
In transaction
ensure ref-set alter commute
Validators
set-validator! get-validator
History
ref-history-count ref-min-history ref-max-history
Agents and Asynchronous Actions (clojure.org/reference/agents)
Create
agent
Examine
agent-error
Change state
send send-off restart-agent send-via
set-agent-send-executor! set-agent-send-off-executor!
Block waiting
await await-for
Ref validators
set-validator! get-validator
Watchers
add-watch remove-watch
Thread handling
shutdown-agents
Error
error-handler set-error-handler! error-mode set-error-mode!
Misc
*agent* release-pending-sends

Java Interoperation (clojure.org/reference/java_interop)


General

Cast
Exceptions
Arrays
Create

Use
Cast

.. doto Classname/ Classname. new bean comparator enumeration-seq


import iterator-seq memfn set! class class? bases supers type
gen-class gen-interface definterface
boolean byte short char int long float double bigdec bigint num
cast biginteger
throw try catch finally pst ex-info ex-data

make-array object-array boolean-array byte-array short-array


char-array int-array long-array float-array double-array aclone
to-array to-array-2d into-array
aget aset aset-boolean aset-byte aset-short aset-char aset-int
aset-long aset-float aset-double alength amap areduce
booleans bytes shorts chars ints longs floats doubles

Proxy (Clojure type selection flowchart)


Create
proxy get-proxy-class construct-proxy init-proxy
Misc
proxy-mappings proxy-super update-proxy

Other
XML
REPL
Code
Misc
Browser
/ Shell

clojure.xml/parse xml-seq
*1 *2 *3 *e *print-dup* *print-length* *print-level* *print-meta*
*print-readably*
*compile-files* *compile-path* *file* *warn-on-reflection* compile
loaded-libs test
eval force hash name *clojure-version* clojure-version
*command-line-args*
(clojure.java.browse/) browse-url (clojure.java.shell/) sh with-sh-dir
with-sh-env

You might also like