Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

clojure2

The Clojure Cheat Sheet provides a comprehensive overview of Clojure functions, data types, and operations across various categories such as primitives, collections, functions, macros, and concurrency. It includes syntax for creating and manipulating data structures like maps, sets, and vectors, as well as key functions for I/O and string handling. Additionally, it covers advanced topics like protocols, records, and Java interoperation, making it a valuable reference for Clojure developers.

Uploaded by

dante.zaupa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

clojure2

The Clojure Cheat Sheet provides a comprehensive overview of Clojure functions, data types, and operations across various categories such as primitives, collections, functions, macros, and concurrency. It includes syntax for creating and manipulating data structures like maps, sets, and vectors, as well as key functions for I/O and string handling. Additionally, it covers advanced topics like protocols, records, and Java interoperation, making it a valuable reference for Clojure developers.

Uploaded by

dante.zaupa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Clojure Cheat Sheet (Clojure 1.3 - 1.

6, sheet v20) Relations (set of maps, each with same keys, aka rels)
Documentation Rel algebra (clojure.set/) join select project union difference
intersection index rename
clojure.repl/ doc find-doc apropos source pst javadoc (foo.bar/ is
namespace for later syms) Transients (clojure.org/transients)
Create transient persistent!
Primitives Change conj! pop! assoc! dissoc! disj! Note: always use return value
Numbers for later changes, never original!
Literals Long: 7, hex 0xff, oct 017, base 2 2r1011, base 36
36rCRAZY BigInt: 7N Ratio: -22/7 Double: 2.78 -1.2e-5 Misc
BigDecimal: 4.2M Compare = == identical? not= not compare clojure.data/diff
Arithmetic + - * / quot rem mod inc dec max min +’ -’ *’ inc’ dec’ Test true? false? instance? nil? (1.6) some?
Compare = == not= < > <= >= compare
Bitwise bit-and bit-or bit-xor bit-not bit-flip bit-set Sequences
bit-shift-right bit-shift-left bit-and-not bit-clear Creating a Lazy Seq
bit-test (1.6) unsigned-bit-shift-right (see BigInteger From collection seq vals keys rseq subseq rsubseq
for integers larger than Long) From producer fn lazy-seq repeatedly iterate
Cast byte short int long float double bigdec bigint num From constant repeat range
rationalize biginteger From other file-seq line-seq resultset-seq re-seq tree-seq
Test zero? pos? neg? even? odd? number? rational? integer? xml-seq iterator-seq enumeration-seq
ratio? decimal? float? From seq keep keep-indexed
Random rand rand-int
BigDecimal with-precision Seq in, Seq out
Unchecked *unchecked-math* unchecked-add unchecked-dec Get shorter distinct filter remove take-nth for
unchecked-inc unchecked-multiply unchecked-negate Get longer cons conj concat lazy-cat mapcat cycle interleave
unchecked-subtract interpose
Tail-items rest nthrest next fnext nnext drop drop-while
Strings take-last for
Create str format See also IO/to string Head-items take take-while butlast drop-last for
Use count get subs compare (clojure.string/) join escape ‘Change’ conj concat distinct flatten group-by partition
split split-lines replace replace-first reverse (1.5) partition-all partition-by split-at split-with filter
re-quote-replacement (String) .indexOf .lastIndexOf remove replace shuffle
Regex #"pattern" re-find re-seq re-matches re-pattern re-matcher Rearrange reverse sort sort-by compare
re-groups (clojure.string/) replace replace-first (1.5) Process items map pmap map-indexed mapcat for replace seque
re-quote-replacement
Letters (clojure.string/) capitalize lower-case upper-case Using a Seq
Trim (clojure.string/) trim trim-newline triml trimr Extract item first second last rest next ffirst nfirst fnext
Test char char? string? (clojure.string/) blank? (String) nnext nth nthnext rand-nth when-first max-key
.startsWith .endsWith .contains min-key
Construct coll zipmap into reduce reductions set vec into-array
Other to-array-2d
Characters char char-name-string char-escape-string Pass to fn apply
Keywords keyword keyword? find-keyword Search some filter
Symbols symbol symbol? gensym Force evaluation doseq dorun doall
Check for forced realized?
Collections
Collections Zippers (clojure.zip/)
Generic ops count empty not-empty into conj (clojure.walk/) walk Create zipper seq-zip vector-zip xml-zip
prewalk prewalk-demo prewalk-replace postwalk Get loc up down left right leftmost rightmost
postwalk-demo postwalk-replace Get seq lefts rights path children
Content tests distinct? empty? every? not-every? some not-any? ‘Change’ make-node replace edit insert-child insert-left
Capabilities sequential? associative? sorted? counted? reversible? insert-right append-child remove
Type tests coll? list? vector? set? map? seq? (1.6) record? Move next prev
Lists Misc root node branch? end?
Create ’() list list*
Examine first nth peek .indexOf .lastIndexOf IO
‘Change’ cons conj rest pop to/from spit slurp (to writer/from reader, Socket, string with file
... name, URI, etc.)
Vectors to *out* pr prn print printf println newline (clojure.pprint/)
Create [] vector vec vector-of print-table
Examine (my-vec idx) → ( nth my-vec idx) get peek .indexOf to writer (clojure.pprint/) pprint cl-format also: (binding [*out*
.lastIndexOf writer] ...)
‘Change’ assoc pop subvec replace conj rseq to string format with-out-str pr-str prn-str print-str
Ops (1.4) mapv filterv reduce-kv println-str
Sets from *in* read-line (clojure.tools.reader.edn/) read
Create #{} set hash-set sorted-set sorted-set-by (flat- from reader line-seq (clojure.tools.reader.edn/) read also: (binding
land.ordered.set/) ordered-set [*in* reader] ...) java.io.Reader
Examine (my-set item) → ( get my-set item) contains? from string with-in-str (clojure.tools.reader.edn/) read-string
‘Change’ conj disj Open with-open (clojure.java.io/) text: reader writer binary:
Set ops (clojure.set/) union difference intersection select See also input-stream output-stream
Relations Binary (.write ostream byte-arr) (.read istream byte-arr)
Test (clojure.set/) subset? superset? java.io.OutputStream java.io.InputStream GitHub: gloss
byte-spec
Maps Misc flush (.close s) file-seq *in* *out* *err* (clo-
Create {} hash-map array-map zipmap sorted-map sorted-map-by jure.java.io/) file copy delete-file resource as-file
bean frequencies group-by (clojure.set/) index (flat- as-url as-relative-path GitHub: fs
land.ordered.map/) ordered-map (clojure.data.priority-map/) Data readers (1.4) *data-readers* default-data-readers (1.5)
priority-map (flatland.useful.map/) ordering-map *default-data-reader-fn*
Examine (:key my-map) → ( get my-map :key) get-in contains?
find keys vals Functions
‘Change’ assoc assoc-in dissoc merge merge-with select-keys Create fn defn defn- definline identity constantly memfn comp
update-in (clojure.set/) rename-keys map-invert GitHub: complement partial juxt memoize fnil every-pred some-fn
Medley Call apply -> ->> trampoline (1.5) as-> cond-> cond->> some->
Entry key val some->>
Sorted maps rseq subseq rsubseq Test fn? ifn?
Abstractions (Clojure type selection flowchart) Namespace
Protocols (clojure.org/protocols) Current *ns*
Define ( defprotocol Slicey (slice [at])) Create/Switch (tutorial) ns in-ns create-ns
Extend ( extend-type String Slicey (slice [at] ...)) Add alias def import intern refer
Extend null ( extend-type nil Slicey (slice [_] nil)) Find all-ns find-ns
Reify ( reify Slicey (slice [at] ...)) Examine ns-name ns-aliases ns-map ns-interns ns-publics
Test satisfies? extends? ns-refers ns-imports
Other extend extend-protocol extenders From symbol resolve ns-resolve namespace the-ns
Remove ns-unalias ns-unmap remove-ns
Records (clojure.org/datatypes)
Define ( defrecord Pair [h t]) Loading
Access (:h (Pair. 1 2)) → 1 Load libs (tutorial) require use import refer
Create Pair. ->Pair map->Pair List loaded loaded-libs
Test record? Load misc load load-file load-reader load-string
Types (clojure.org/datatypes) Concurrency
Define ( deftype Pair [h t]) Atoms atom swap! reset! compare-and-set!
Access (.h (Pair. 1 2)) → 1 Futures future future-call future-done? future-cancel
Create Pair. ->Pair future-cancelled? future?
( deftype Pair [h t] Threads bound-fn bound-fn* get-thread-bindings
With methods Object push-thread-bindings pop-thread-bindings thread-bound?
(toString [this] (str "<" h "," t ">"))) Misc locking pcalls pvalues pmap seque promise deliver
Multimethods (clojure.org/multimethods) Refs and Transactions (clojure.org/refs)
Define ( defmulti my-mm dispatch-fn) Create ref
Method define ( defmethod my-mm :dispatch-value [args] ...) Examine deref @ (@form → (deref form))
Dispatch get-method methods Transaction sync dosync io!
Remove remove-method remove-all-methods In transaction ensure ref-set alter commute
Prefer prefer-method prefers Validators set-validator! get-validator
Relation derive isa? parents ancestors descendants History ref-history-count ref-min-history ref-max-history
make-hierarchy
Agents and Asynchronous Actions (clojure.org/agents)
Create agent
Macros
Examine agent-error
Create defmacro definline
Change state send send-off restart-agent (1.5)
Debug macroexpand-1 macroexpand (clojure.walk/) macroexpand-all
send-via set-agent-send-executor!
Branch and or when when-not when-let when-first if-not if-let
set-agent-send-off-executor!
cond condp case (1.6) when-some if-some
Block waiting await await-for
Loop for doseq dotimes while
Ref validators set-validator! get-validator
Arrange .. doto -> ->> (1.5) as-> cond-> cond->> some-> some->>
Watchers add-watch remove-watch
Scope binding locking time with-in-str with-local-vars with-open
Thread handling shutdown-agents
with-out-str with-precision with-redefs with-redefs-fn
Error error-handler set-error-handler! error-mode
Lazy lazy-cat lazy-seq delay
set-error-mode!
Doc. assert comment doc
Misc *agent* release-pending-sends

Reader Macros (clojure.org/reader) Java Interoperation (clojure.org/java_interop)


’ quote: ’form → ( quote form) General .. doto Classname/ Classname. new bean comparator
\ Character literal enumeration-seq import iterator-seq memfn set! class
; Single line comment class? bases supers type
ˆ Metadata (see Metadata section) Cast boolean byte short char int long float double bigdec
@ Deref: @form → ( deref form) bigint num cast biginteger
‘ Syntax-quote Exceptions throw try catch finally pst (1.4) ex-info ex-data
~ Unquote Arrays
~@ Unquote-splicing
Create make-array object-array boolean-array byte-array
#"p" Regex Pattern p (see Strings/Regex section)
short-array char-array int-array long-array float-array
#′ Var-quote #′ x → ( var x)
double-array aclone to-array to-array-2d into-array
#() Anonymous function literal: #(...) → (fn [args] (...))
Use aget aset aset-boolean aset-byte aset-short aset-char
#_ Ignore next form
aset-int aset-long aset-float aset-double alength amap
areduce
Metadata (clojure.org/reader, special_forms) Cast booleans bytes shorts chars ints longs floats doubles
General ˆ{:key1 val1 :key2 val2 ...} Proxy (Clojure type selection flowchart)
Abbrevs ˆType → ˆ{:tag Type}, ˆ:key → ˆ{:key true} Create proxy get-proxy-class construct-proxy init-proxy
Common ˆ:dynamic ˆ:private ˆ:doc ˆ:const Misc proxy-mappings proxy-super update-proxy
Examples (defn ˆ:private ˆString my-fn ...) (def ˆ:dynamic
*dyn-var* val) Other
On Vars meta with-meta vary-meta alter-meta! reset-meta! doc XML clojure.xml/parse xml-seq
find-doc test REPL *1 *2 *3 *e *print-dup* *print-length* *print-level*
*print-meta* *print-readably*
Special Forms (clojure.org/special_forms) Code *compile-files* *compile-path* *file* *warn-on-reflection*
compile gen-class gen-interface loaded-libs test
def if do let letfn quote var fn loop recur set! throw try Misc eval force hash name *clojure-version* clojure-version
monitor-enter monitor-exit *command-line-args*
Binding Forms / (examples) let fn defn defmacro loop for doseq Browser (clojure.java.browse/) browse-url (clojure.java.shell/) sh
Destructuring if-let when-let (1.6) if-some when-some / Shell with-sh-dir with-sh-env

Vars and global environment (clojure.org/vars)


Def variants def defn defn- definline defmacro defmethod defmulti
defonce defrecord
Interned vars declare intern binding find-var var
Var objects with-local-vars var-get var-set alter-var-root var?
bound? thread-bound?
Var validators set-validator! get-validator

You might also like