Clojure

チートシート

Clojure 1.11 チートシート (v54)

PDF版ダウンロード / ソースリポジトリ

作成:Steve Tayon氏、継続的なメンテナンス:Andy Fingerhut氏、両氏に多謝。

ドキュメント

clojure.repl/ doc find-doc apropos dir source pst javadoc (foo.bar/ は以降のシンボルの名前空間)

プリミティブ

数値

リテラル Long:7、16進数 0xff、8進数 017、2進数 2r1011、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' (1.11) abs
比較 == < > <= >= 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 unsigned-bit-shift-right (BigInteger を参照 Longより大きい整数の場合)
キャスト byte short int long float double bigdec bigint num rationalize biginteger
テスト zero? pos? neg? even? odd? number? rational? integer? ratio? decimal? float? (1.9) double? int? nat-int? neg-int? pos-int? (1.11) NaN? infinite?
乱数 rand rand-int
BigDecimal with-precision
チェックなし *unchecked-math* unchecked-add unchecked-dec unchecked-inc unchecked-multiply unchecked-negate unchecked-subtract

文字列

作成 str format "a string" "エスケープ \b\f\n\t\r\" 8進数 \377 16進数 \ucafe" IO/to string セクションも参照してください。
使用 count get subs compare (clojure.string/) join escape split split-lines replace replace-first reverse index-of last-index-of (1.11) (clojure.core/) parse-boolean parse-double parse-long parse-uuid
正規表現 #"pattern" re-find re-seq re-matches re-pattern re-matcher re-groups (clojure.string/) replace replace-first re-quote-replacement 注:#""内の\はエスケープ文字ではありません。(re-pattern "\\s*\\d+")#"\s*\d+"と書くことができます。
文字 (clojure.string/) capitalize lower-case upper-case
トリム (clojure.string/) trim trim-newline triml trimr
テスト string? (clojure.string/) blank? starts-with? ends-with? includes?

その他

文字 char char? char-name-string char-escape-string リテラル:\a \newline (詳細はリンク先を参照)
キーワード keyword keyword? find-keyword リテラル::kw :my.name.space/kw ::in-cur-namespace ::namespace-alias/kw
シンボル symbol symbol? gensym リテラル:my-sym my.ns/foo
その他 リテラル:true false nil

コレクション

コレクション

汎用演算 count empty not-empty into conj (clojure.walk/) walk prewalk prewalk-demo prewalk-replace postwalk postwalk-demo postwalk-replace (1.9) bounded-count
コンテンツテスト distinct? empty? every? not-every? some not-any?
機能 sequential? associative? sorted? counted? reversible?
型テスト coll? list? vector? set? map? seq? record? map-entry?

リスト(先頭でのconj、pop、peek)

作成 () list list*
検査 first nth peek .indexOf .lastIndexOf
変更 cons conj rest pop

ベクター(末尾でのconj、pop、peek)

作成 [] vector vec vector-of mapv filterv
検査 (my-vec idx)( nth my-vec idx) get peek .indexOf .lastIndexOf
変更 assoc assoc-in pop subvec replace conj rseq update update-in
演算 reduce-kv

集合

ソートされていない集合の作成 #{} set hash-set
ソート済み集合の作成 sorted-set sorted-set-by (clojure.data.avl/) sorted-set sorted-set-by (flatland.ordered.set/) ordered-set (clojure.data.int-map/) int-set dense-int-set
検査 (my-set item)( get my-set item) contains?
変更 conj disj
集合演算 (clojure.set/) union difference intersection select 関連セクションも参照してください
テスト (clojure.set/) subset? superset?
ソート済み集合 rseq subseq rsubseq

マップ

ソートされていない集合の作成 {} 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) また (:key my-map)( get my-map :key) get-in contains? find keys vals
変更 assoc assoc-in dissoc merge merge-with select-keys update update-in (clojure.set/) rename-keys map-invert (1.11) (clojure.core/) update-keys update-vals GitHub: Medley
演算 reduce-kv
エントリ key val
ソート済みマップ rseq subseq rsubseq

キュー(最後にconj、先頭からpeekとpop)

作成 clojure.lang.PersistentQueue/EMPTY(リテラル構文またはコンストラクタ関数はありません)
検査 peek
変更 conj pop

リレーション(マップのセット。それぞれ同じキーを持つ、別名rels)

関係代数 (clojure.set/) join select project union difference intersection index rename

トランジェント(clojure.org/reference/transients

作成 transient persistent!
変更 conj! pop! assoc! dissoc! disj! 注:後続の変更には常に戻り値を使用し、元の値は決して使用しないでください!

その他

比較 = identical? not= not compare clojure.data/diff
テスト true? false? instance? nil? some?

シーケンス

遅延シーケンスの作成

コレクションから seq vals keys rseq subseq rsubseq sequence
プロデューサ関数から lazy-seq repeatedly iterate (1.11) iteration
定数から repeat range
その他から file-seq line-seq resultset-seq re-seq tree-seq xml-seq iterator-seq enumeration-seq
seq から keep keep-indexed

入力seq、出力seq

短縮 distinct filter remove take-nth for dedupe random-sample
長くする 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

シーケンスの使用

要素の抽出 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 run!
強制されたかの確認 realized?

トランスデューサ (clojure.org/reference/transducers)

既製の関数 map mapcat filter remove take take-while take-nth drop drop-while replace partition-by partition-all keep keep-indexed map-indexed distinct interpose cat dedupe random-sample (1.9) halt-when
独自の作成 completing ensure-reduced unreduced 同時実行/揮発性セクションも参照してください。
使用 into sequence transduce eduction
早期終了 reduced reduced? deref

Spec (理論的根拠ガイド)

操作 valid? conform unform explain explain-data explain-str explain-out form describe assert check-asserts check-asserts?
ジェネレータ操作 gen gen exercise exercise exercise-fn exercise-fn
定義とレジストリ def def fdef fdef registry registry get-spec get-spec spec? spec? spec spec with-gen with-gen
論理演算 and and or or
コレクション coll-of coll-of map-of map-of every every every-kv every-kv keys keys merge merge
正規表現 cat cat alt alt * * + + ? ? & & keys* keys*
範囲 int-in inst-in double-in int-in-range? inst-in-range?
その他 nilable multi-spec fspec conformer
カスタム説明 explain-printer *explain-out*

test.checkジェネレーターを使用した述語

数値 number? rational? integer? ratio? decimal? float? zero? (1.9) double? int? nat-int? neg-int? pos-int?
シンボル、キーワード keyword? symbol? (1.9) ident? qualified-ident? qualified-keyword? qualified-symbol? simple-ident? simple-keyword? simple-symbol?
その他のスカラー string? true? false? nil? some? (1.9) boolean? bytes? inst? uri? uuid?
コレクション list? map? set? vector? associative? coll? sequential? seq? empty? (1.9) indexed? seqable?
その他 (1.9) any?

入出力

to/from ... spit slurp (ライターへの書き込み/リーダーからの読み取り、ソケット、ファイル名付き文字列、URIなど)
*out*への書き込み pr prn print printf println newline (clojure.pprint/) print-table
ライターへの書き込み (clojure.pprint/) pprint cl-format その他: (binding [*out* writer] ...)
文字列へ format with-out-str pr-str prn-str print-str println-str
*in*から read-line (clojure.edn/) read (clojure.tools.reader.edn/) read
リーダーから line-seq (clojure.edn/) read (clojure.tools.reader.edn/) read その他: (binding [*in* reader] ...) java.io.Reader
文字列から with-in-str (clojure.edn/) read-string (clojure.tools.reader.edn/) read-string
オープン with-open (clojure.java.io/) テキスト: reader writer バイナリ: 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*
tap (1.10) tap> add-tap remove-tap

抽象化(Clojure型選択フローチャート

プロトコル(clojure.org/reference/protocols

定義 ( defprotocol Slicey (slice [at]))
拡張 ( extend-type String Slicey (slice [at] ...))
nullの拡張 ( extend-type nil Slicey (slice [_] nil))
Reify ( reify Slicey (slice [at] ...))
テスト satisfies? extends?
その他 extend extend-protocol extenders

レコード(clojure.org/reference/datatypes

定義 ( defrecord Pair [h t])
アクセス (:h (Pair. 1 2))1
作成 Pair. ->Pair map->Pair
テスト record?

型(clojure.org/reference/datatypes

定義 ( deftype Pair [h t])
アクセス (.h (Pair. 1 2))1
作成 Pair. ->Pair
メソッド付き ( deftype Pair [h t]
  Object
  (toString [this] (str "<" h "," t ">")))

マルチメソッド(clojure.org/reference/multimethods

定義 ( defmulti my-mm dispatch-fn)
メソッド定義 ( defmethod my-mm :dispatch-value [args] ...)
ディスパッチ get-method methods
削除 remove-method remove-all-methods
優先順位 prefer-method prefers
関係 derive underive isa? parents ancestors descendants make-hierarchy

Datafy (記事)

Datafy (clojure.datafy/) datafy nav

特殊文字 (clojure.org/reference/reader, ガイド)

, コンマは空白として読み取られます。可読性のために、多くの場合、マップのキー/値ペアの間に使用されます。
' 引用: 'form( quote form)
/ 名前空間セパレータ(プリミティブ/その他セクションを参照)
\ 文字リテラル(プリミティブ/その他セクションを参照)
: キーワード(プリミティブ/その他セクションを参照)
; シングルラインコメント
^ メタデータ(メタデータセクションを参照)
*foo* 'earmuffs' - 動的変数を示す慣例、動的でない場合、コンパイラは警告します。
@ デリファレンス: @form( deref form)
` シンタックスクォート
foo# 'auto-gensym' 同一の `( ... ) 内では、常に同じ自動生成シンボルに置き換えられます。
~ アンクォート
~@ アンクォートスプライシング
-> 'thread first' マクロ ->
->> 'thread last' マクロ ->>
>!! <!! >! <! core.async チャンネルマクロ >!! <!! >! <!
( リストリテラル(コレクション/リストセクションを参照)
[ ベクターリテラル(コレクション/ベクターセクションを参照)
{ マップリテラル(コレクション/マップセクションを参照)
#' Varクォート: #'x( var x)
#" #"p" は正規表現パターンpとして読み取られます(文字列/正規表現セクションを参照)。
#{ 集合リテラル(コレクション/集合セクションを参照)。
#( 匿名関数リテラル: #(...)(fn [args] (...))
% 匿名関数の引数: %N は匿名関数の引数Nの値です。%%1の省略形です。%&はrest引数です。
#? リーダ条件式: #?(:clj x :cljs y) はJVMではx、ClojureScriptではy、それ以外の環境では何も読み取られません。その他のキー: :cljr :default
#?@ スプライシングリーダ条件式: [1 #?@(:clj [x y] :cljs [w z]) 3] はJVMでは[1 x y 3]、ClojureScriptでは[1 w z 3]、それ以外の環境では[1 3]として読み取られます。
#foo タグ付きリテラル 例: #inst #uuid
#: マップ名前空間構文 例: #:foo{:a 1}{:foo/a 1} と等価です。
## (1.9) 記号値: ##Inf ##-Inf ##NaN
$ JavaContainerClass$InnerClass
foo? 述語の慣例的な接尾辞、例: zero? vector? instance?(強制されない)。
foo! 安全でない操作の慣例的な接尾辞、例: set! swap! alter-meta!(強制されない)。
_ 使用されない値の慣例的な名前(強制されない)。
#_ 次のフォームを無視する。

メタデータ(clojure.org/reference/readerspecial_forms)。

一般 ^{:key1 val1 :key2 val2 ...}
略記 ^Type^{:tag Type}
^:key^{:key true}
共通 ^:dynamic ^:private ^:doc ^:const
(defn ^:private ^String my-fn ...)
(def ^:dynamic *dyn-var* val)
Varについて meta with-meta vary-meta alter-meta! reset-meta! doc find-doc test

特殊形式(clojure.org/reference/special_forms)。

バインディングフォーム/デストラクチャリング () https://clojure.dokyumento.jp/reference/special_forms#binding-forms を参照してください。 https://clojure.dokyumento.jp/special_forms#let も参照してください。Spec args: (cat :bindings :clojure.core.specs.alpha/bindings :body (* any?)) ret: any?">let https://clojure.dokyumento.jp/reference/special_forms#fn を参照してください。 https://clojure.dokyumento.jp/special_forms#fn も参照してください。Spec args: (cat :fn-name (? simple-symbol?) :fn-tail (alt :arity-1 :clojure.core.specs.alpha/params+body :arity-n (+ (spec :clojure.core.specs.alpha/params+body)))) ret: any?">fn defn defmacro https://clojure.dokyumento.jp/special_forms#loopを参照してください。">loop for doseq if-let when-let if-some when-some

Varとグローバル環境(clojure.org/reference/vars)

defのバリエーション https://clojure.dokyumento.jp/special_forms#defを参照してください。">def defn defn- definline defmacro defmethod defmulti defonce defrecord
インターニングされたVar declare intern binding find-var https://clojure.dokyumento.jp/special_forms#varを参照してください。">var
Varオブジェクト with-local-vars var-get var-set alter-var-root var? bound? thread-bound?
Varバリデータ set-validator! get-validator

読み込み

ライブラリの読み込み (チュートリアル) require use import refer
ロード済みリスト ロード済みライブラリ
その他をロード load load-file load-reader load-string

並行処理

アトム atom swap! reset! compare-and-set! (1.9) swap-vals! reset-vals!
フューチャー 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?
ボラタイル volatile! vreset! vswap! volatile?
その他 locking pcalls pvalues pmap seque promise deliver

Refとトランザクション (clojure.org/reference/refs)

作成 ref
検査 deref @ (@form(deref form))
トランザクション sync dosync io!
トランザクション内 ensure ref-set alter commute
バリデータ set-validator! get-validator
履歴 ref-history-count ref-min-history ref-max-history

エージェントと非同期アクション (clojure.org/reference/agents)

作成 agent
検査 agent-error
状態変更 send send-off restart-agent send-via set-agent-send-executor! set-agent-send-off-executor!
ブロッキング待ち await await-for
Refバリデータ set-validator! get-validator
ウォッチャー add-watch remove-watch
スレッド処理 shutdown-agents
エラー error-handler set-error-handler! error-mode set-error-mode!
その他 *agent* release-pending-sends

ジッパー関数 (clojure.zip/)

作成 zipper seq-zip vector-zip xml-zip
位置取得関数 up down left right leftmost rightmost
シーケンス取得関数 lefts rights path children
変更 make-node replace edit insert-child insert-left insert-right append-child remove
移動 next prev
その他 root node branch? end?