0% found this document useful (0 votes)
55 views

Cheatsheet Usletter Color

This document provides a cheat sheet summarizing key concepts in Clojure including: 1) It outlines core data types like numbers, strings, collections and operations that can be performed on them. It describes primitives like vectors, lists, sets and maps as well as functions for creating, examining and changing them. 2) It covers common functional programming concepts in Clojure like lazy sequences, transients, relations and transducer functions. 3) It provides an overview of Clojure's spec library for defining and validating data along with examples of common spec operations and predicates.

Uploaded by

Bogdan Ivanov
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)
55 views

Cheatsheet Usletter Color

This document provides a cheat sheet summarizing key concepts in Clojure including: 1) It outlines core data types like numbers, strings, collections and operations that can be performed on them. It describes primitives like vectors, lists, sets and maps as well as functions for creating, examining and changing them. 2) It covers common functional programming concepts in Clojure like lazy sequences, transients, relations and transducer functions. 3) It provides an overview of Clojure's spec library for defining and validating data along with examples of common spec operations and predicates.

Uploaded by

Bogdan Ivanov
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.6 - 1.

9, sheet v44) Relations (set of maps, each with same keys, aka rels)
Rel algebra (clojure.set/) join select project union difference intersection index
rename
Documentation
clojure.repl/ doc find-doc apropos dir source pst javadoc (foo.bar/ is namespace Transients (clojure.org/reference/transients)
for later syms) Create transient persistent!
Change conj! pop! assoc! dissoc! disj! Note: always use return value for later changes,
never original!

Primitives Misc
Compare = identical? not= not compare clojure.data/diff
Numbers Test true? false? instance? nil? some?
Literals 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
Arithmetic + - * / quot rem mod inc dec max min +’ -’ *’ inc’ dec’ Sequences
Compare == < > <= >= compare Creating a Lazy Seq
Bitwise bit-and bit-or bit-xor bit-not bit-flip bit-set From collection seq vals keys rseq subseq rsubseq sequence
bit-shift-right bit-shift-left bit-and-not bit-clear bit-test From producer fn lazy-seq repeatedly iterate
unsigned-bit-shift-right (see BigInteger for integers larger than From constant repeat range
Long) From other file-seq line-seq resultset-seq re-seq tree-seq xml-seq
Cast byte short int long float double bigdec bigint num rationalize iterator-seq enumeration-seq
biginteger From seq keep keep-indexed
Test zero? pos? neg? even? odd? number? rational? integer? ratio?
decimal? float? (1.9) double? int? nat-int? neg-int? pos-int? Seq in, Seq out
Random rand rand-int Get shorter distinct filter remove take-nth for (1.7) dedupe random-sample
BigDecimal with-precision Get longer cons conj concat lazy-cat mapcat cycle interleave interpose
Unchecked *unchecked-math* unchecked-add unchecked-dec unchecked-inc Tail-items rest nthrest next fnext nnext drop drop-while take-last for
unchecked-multiply unchecked-negate unchecked-subtract Head-items take take-while butlast drop-last for
‘Change’ conj concat distinct flatten group-by partition partition-all
Strings
partition-by split-at split-with filter remove replace shuffle
Create str format "a string" "escapes \b\f\n\t\r\" octal \377 hex \ucafe" See Rearrange reverse sort sort-by compare
also section IO/to string Process items map pmap map-indexed mapcat for replace seque
Use count get subs compare (clojure.string/) join escape split split-lines
replace replace-first reverse (1.8) index-of last-index-of Using a Seq
Regex #"pattern" re-find re-seq re-matches re-pattern re-matcher re-groups Extract item first second last rest next ffirst nfirst fnext nnext nth
(clojure.string/) replace replace-first re-quote-replacement Note: \ in #"" nthnext rand-nth when-first max-key min-key
is not escape char. (re-pattern "\\s*\\d+") can be written #"\s*\d+" Construct coll zipmap into reduce reductions set vec into-array to-array-2d
Letters (clojure.string/) capitalize lower-case upper-case mapv filterv
Trim (clojure.string/) trim trim-newline triml trimr Pass to fn apply
Test string? (clojure.string/) blank? (1.8) starts-with? ends-with? includes? Search some filter
Force evaluation doseq dorun doall (1.7) run!
Other
Check for forced realized?
Characters char char? char-name-string char-escape-string literals: \a \newline
(more at link)
Keywords keyword keyword? find-keyword literals: :kw :my.name.space/kw Transducers (clojure.org/reference/transducers)
::in-cur-namespace ::namespace-alias/kw
Off the shelf map mapcat filter remove take take-while take-nth drop
Symbols symbol symbol? gensym literals: my-sym my.ns/foo
drop-while replace partition-by partition-all keep keep-indexed
Misc literals: true false nil
map-indexed distinct interpose (1.7) cat dedupe random-sample
(1.9) halt-when
Create your own (1.7) completing ensure-reduced unreduced See also section Concur-
rency/Volatiles
Collections
Use into sequence (1.7) transduce eduction
Collections Early termination reduced reduced? deref
Generic ops count empty not-empty into conj (clojure.walk/) walk prewalk
prewalk-demo prewalk-replace postwalk postwalk-demo
postwalk-replace (1.9) bounded-count Spec (rationale, guide)
Content tests distinct? empty? every? not-every? some not-any? Operations valid? conform unform explain explain-data explain-str
Capabilities sequential? associative? sorted? counted? reversible? explain-out form describe assert check-asserts check-asserts?
Type tests coll? list? vector? set? map? seq? record? (1.8) map-entry? Generator ops gen exercise exercise-fn
Defn. & registry def fdef registry get-spec spec? spec with-gen
Lists (conj, pop, & peek at beginning)
Logical and or
Create () list list* Collection coll-of map-of every every-kv keys merge
Examine first nth peek .indexOf .lastIndexOf Regex cat alt * + ? & keys*
‘Change’ cons conj rest pop Range int-in inst-in double-in int-in-range? inst-in-range?
Vectors (conj, pop, & peek at end) Other nilable multi-spec fspec conformer
Custom explain explain-printer *explain-out*
Create [] vector vec vector-of mapv filterv (clojure.core.rrb-vector/) vector vec
vector-of Predicates with test.check generators
Examine (my-vec idx) → ( nth my-vec idx) get peek .indexOf .lastIndexOf Numbers number? rational? integer? ratio? decimal? float? zero? (1.9)
‘Change’ assoc assoc-in pop subvec replace conj rseq update-in (1.7) update double? int? nat-int? neg-int? pos-int?
Ops reduce-kv Symbols, keyword? symbol? (1.9) ident? qualified-ident? qualified-keyword?
keywords qualified-symbol? simple-ident? simple-keyword? simple-symbol?
Sets
Other string? true? false? nil? some? (1.9) boolean? bytes? inst? uri?
Create unsorted #{} set hash-set
scalars uuid?
Create sorted sorted-set sorted-set-by (clojure.data.avl/) sorted-set
Collections list? map? set? vector? associative? coll? sequential? seq? empty?
sorted-set-by (flatland.ordered.set/) ordered-set (clojure.data.int-
(1.9) indexed? seqable?
map/) int-set dense-int-set
Other (1.9) any?
Examine (my-set item) → ( get my-set item) contains?
‘Change’ conj disj
Set ops (clojure.set/) union difference intersection select See also section IO
Relations to/from spit slurp (to writer/from reader, Socket, string with file name, URI, etc.)
Test (clojure.set/) subset? superset? ...
Sorted sets rseq subseq rsubseq to *out* pr prn print printf println newline (clojure.pprint/) print-table
to writer (clojure.pprint/) pprint cl-format also: (binding [*out* writer] ...)
Maps
to string format with-out-str pr-str prn-str print-str println-str
Create unsorted {} hash-map array-map zipmap bean frequencies group-by (clo- from *in* read-line (clojure.tools.reader.edn/) read
jure.set/) index from reader line-seq (clojure.tools.reader.edn/) read also: (binding [*in* reader]
Create sorted sorted-map sorted-map-by (clojure.data.avl/) sorted-map ...) java.io.Reader
sorted-map-by (flatland.ordered.map/) ordered-map from string with-in-str (clojure.tools.reader.edn/) read-string
(clojure.data.priority-map/) priority-map (flatland.useful.map/) Open with-open (clojure.java.io/) text: reader writer binary: input-stream
ordering-map (clojure.data.int-map/) int-map output-stream
Examine (my-map k) → ( get my-map k) also (:key my-map) → ( get Binary (.write ostream byte-arr) (.read istream byte-arr)
my-map :key) get-in contains? find keys vals java.io.OutputStream java.io.InputStream GitHub: gloss byte-spec
‘Change’ assoc assoc-in dissoc merge merge-with select-keys update-in Misc flush (.close s) file-seq *in* *out* *err* (clojure.java.io/) file
(1.7) update (clojure.set/) rename-keys map-invert GitHub: Medley copy delete-file resource as-file as-url as-relative-path GitHub:
Ops reduce-kv fs
Entry key val Data readers *data-readers* default-data-readers *default-data-reader-fn*
Sorted maps rseq subseq rsubseq

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


Create clojure.lang.PersistentQueue/EMPTY (no literal syntax or constructor Create fn defn defn- definline identity constantly memfn comp complement
fn) partial juxt memoize fnil every-pred some-fn
Examine peek Call apply -> ->> trampoline as-> cond-> cond->> some-> some->>
’Change’ conj pop Test fn? ifn?
Abstractions (Clojure type selection flowchart) Vars and global environment (clojure.org/reference/vars)
Protocols (clojure.org/reference/protocols) Def variants def defn defn- definline defmacro defmethod defmulti defonce
Define ( defprotocol Slicey (slice [at])) defrecord
Extend ( extend-type String Slicey (slice [at] ...)) Interned vars declare intern binding find-var var
Extend null ( extend-type nil Slicey (slice [_] nil)) Var objects with-local-vars var-get var-set alter-var-root var? bound?
Reify ( reify Slicey (slice [at] ...)) thread-bound?
Test satisfies? extends? Var validators set-validator! get-validator
Other extend extend-protocol extenders
Namespace
Records (clojure.org/reference/datatypes)
Current *ns*
Define ( defrecord Pair [h t]) Create/Switch (tutorial) ns in-ns create-ns
Access (:h (Pair. 1 2)) → 1 Add alias def import intern refer
Create Pair. ->Pair map->Pair Find all-ns find-ns
Test record? Examine ns-name ns-aliases ns-map ns-interns ns-publics ns-refers
Types (clojure.org/reference/datatypes) ns-imports
From symbol resolve ns-resolve namespace the-ns
Define ( deftype Pair [h t])
Remove ns-unalias ns-unmap remove-ns
Access (.h (Pair. 1 2)) → 1
Create Pair. ->Pair
( deftype Pair [h t]
Loading
With methods Object Load libs (tutorial) require use import refer
(toString [this] (str "<" h "," t ">"))) List loaded loaded-libs
Load misc load load-file load-reader load-string
Multimethods (clojure.org/reference/multimethods)
Define ( defmulti my-mm dispatch-fn) Concurrency
Method define ( defmethod my-mm :dispatch-value [args] ...) Atoms atom swap! reset! compare-and-set! (1.9) swap-vals! reset-vals!
Dispatch get-method methods Futures future future-call future-done? future-cancel future-cancelled?
Remove remove-method remove-all-methods future?
Prefer prefer-method prefers Threads bound-fn bound-fn* get-thread-bindings push-thread-bindings
Relation derive underive isa? parents ancestors descendants make-hierarchy pop-thread-bindings thread-bound?
Volatiles (1.7) volatile! vreset! vswap! volatile?
Macros Misc locking pcalls pvalues pmap seque promise deliver
Create defmacro definline
Refs and Transactions (clojure.org/reference/refs)
Debug macroexpand-1 macroexpand (clojure.walk/) macroexpand-all
Branch and or when when-not when-let when-first if-not if-let cond condp case Create ref
when-some if-some Examine deref @ (@form → (deref form))
Loop for doseq dotimes while Transaction sync dosync io!
Arrange .. doto -> ->> as-> cond-> cond->> some-> some->> In transaction ensure ref-set alter commute
Scope binding locking time with-in-str with-local-vars with-open with-out-str Validators set-validator! get-validator
with-precision with-redefs with-redefs-fn History ref-history-count ref-min-history ref-max-history
Lazy lazy-cat lazy-seq delay
Agents and Asynchronous Actions (clojure.org/reference/agents)
Doc. assert comment doc
Create agent
Examine agent-error
Special Characters (clojure.org/reference/reader, guide) Change state send send-off restart-agent send-via set-agent-send-executor!
, Comma reads as white space. Often used between map key/value pairs for set-agent-send-off-executor!
readability. Block waiting await await-for
’ quote: ’form → ( quote form) Ref validators set-validator! get-validator
/ Namespace separator (see Primitives/Other section) Watchers add-watch remove-watch
\ Character literal (see Primitives/Other section) Thread handling shutdown-agents
: Keyword (see Primitives/Other section) Error error-handler set-error-handler! error-mode set-error-mode!
; Single line comment Misc *agent* release-pending-sends
ˆ Metadata (see Metadata section)
*foo* ’earmuffs’ - convention to indicate dynamic vars, compiler warns Java Interoperation (clojure.org/reference/java_interop)
if not dynamic General .. doto Classname/ Classname. new bean comparator enumeration-seq
@ Deref: @form → ( deref form) import iterator-seq memfn set! class class? bases supers type
‘ Syntax-quote gen-class gen-interface definterface
foo# ’auto-gensym’, consistently replaced with same auto-generated Cast boolean byte short char int long float double bigdec bigint num cast
symbol everywhere inside same ‘( ... ) biginteger
~ Unquote Exceptions throw try catch finally pst ex-info ex-data (1.9)
~@ Unquote-splicing StackTraceElement->vec
-> ’thread first’ macro ->
->> ’thread last’ macro ->> Arrays
>!! <!! >! <! core.async channel macros >!! <!! >! <! Create make-array object-array boolean-array byte-array short-array char-array
( List literal (see Collections/Lists section) int-array long-array float-array double-array aclone to-array
[ Vector literal (see Collections/Vectors section) to-array-2d into-array
{ Map literal (see Collections/Maps section) Use aget aset aset-boolean aset-byte aset-short aset-char aset-int aset-long
#’ Var-quote #’x → ( var x) aset-float aset-double alength amap areduce
#" #"p" reads as regex pattern p (see Strings/Regex section) Cast booleans bytes shorts chars ints longs floats doubles
#{ Set literal (see Collections/Sets section)
#( Anonymous function literal: #(...) → (fn [args] (...)) Proxy (Clojure type selection flowchart)
% Anonymous function argument: %N is value of anonymous function Create proxy get-proxy-class construct-proxy init-proxy
arg N. % short for %1. %& for rest args. Misc proxy-mappings proxy-super update-proxy
#? (1.7) Reader conditional: #?(:clj x :cljs y) reads as x on
JVM, y in ClojureScript, nothing elsewhere. Other keys: :cljr Zippers (clojure.zip/)
:default
Create zipper seq-zip vector-zip xml-zip
#?@ (1.7) Splicing reader conditional: [1 #?@(:clj [x y] :cljs [w
Get loc up down left right leftmost rightmost
z]) 3] reads as [1 x y 3] on JVM, [1 w z 3] in ClojureScript, [1
Get seq lefts rights path children
3] elsewhere.
‘Change’ make-node replace edit insert-child insert-left insert-right
#foo tagged literal e.g. #inst #uuid
append-child remove
$ JavaContainerClass$InnerClass
Move next prev
foo? conventional ending for a predicate, e.g.: zero? vector?
Misc root node branch? end?
instance? (unenforced)
foo! conventional ending for an unsafe operation, e.g.: set! swap!
alter-meta! (unenforced)
Other
_ conventional name for an unused value (unenforced) XML clojure.xml/parse xml-seq
#_ Ignore next form REPL *1 *2 *3 *e *print-dup* *print-length* *print-level* *print-meta*
*print-readably*
Code *compile-files* *compile-path* *file* *warn-on-reflection* compile
Metadata (clojure.org/reference/reader, special_forms) loaded-libs test
General ˆ{:key1 val1 :key2 val2 ...} Misc eval force hash name *clojure-version* clojure-version
Abbrevs ˆType → ˆ{:tag Type}, ˆ:key → ˆ{:key true} *command-line-args*
Common ˆ:dynamic ˆ:private ˆ:doc ˆ:const Browser (clojure.java.browse/) browse-url (clojure.java.shell/) sh with-sh-dir
Examples (defn ˆ:private ˆString my-fn ...) (def ˆ:dynamic *dyn-var* val) / Shell with-sh-env
On Vars meta with-meta vary-meta alter-meta! reset-meta! doc find-doc test

Special Forms (clojure.org/reference/special_forms)


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 when-let
Destructuring if-some when-some

You might also like