Clojure小ネタ
Clojure小ネタ
Clojureのテストはrepl.itというサイトでWEB上で試せる
repl.it - Online REPL, Compiler & IDE
ハッシュマップの型
- {:key "value"} のような形のハッシュマップは、内部ではPersistentHashMapやPersistentArrayMap, PersistentTreeMapのような型を持ちます。
Clojure 1.8.0 Java HotSpot(TM) 64-Bit Server VM 1.8.0_91-b14 (def m {:no "1" :name "山田" :tel "xxx-xxx-xxxx"}) => #'user/m (println m) {:no 1, :name 山田, :tel xxx-xxx-xxxx} => nil (println (type m)) clojure.lang.PersistentArrayMap => nil
マップの操作
- キー/バリューの取り出し
- keys, vals が使える
(vals m) => ("1" "山田" "xxx-xxx-xxxx") (keys m) => (:no :name :tel)
- 順序を変えた取り出し
(map (fn [key] (key m)) [:no :name :tel]) => ("1" "山田" "xxx-xxx-xxxx") (map (fn [key] (key m)) [:tel :name :no]) => ("xxx-xxx-xxxx" "山田" "1")
- キーの削除
- dissoc を使う
(dissoc m :no) => {:name "山田", :tel "xxx-xxx-xxxx"}
- 複数キーの削除
apply を使うとうまくいくapply無しでも動きました、何かと勘違いしていた?
(dissoc m [:no :name]) => {:tel "xxx-xxx-xxxx"}