从Clojure中的嵌套结构获取的惯用法

Con*_*nan 2 clojure

哪一个更具惯用性Clojure?

(def book {:title "Joy of Clojure" 
           :authors ["Michael Fogus" "Chris Houser"]})

(get-in book [:authors 0])
;; => "Michael Fogus"

(-> book :authors first)
;; => "Michael Fogus"
Run Code Online (Sandbox Code Playgroud)

当我有更复杂的数据结构时,这变得更加相关.据推测,两者之间没有技术差异?

noi*_*ith 6

get-in对于嵌套结构更好,因为许多有趣的键不可调用,特别是向量中的索引(除了firstor second)或哈希映射中的字符串键.

user=> (get-in [{:a 0} 1 nil "unknown" {:b {"context info" 42}}] [4 :b "context info"])
42
Run Code Online (Sandbox Code Playgroud)

  • 如果密钥不存在,还允许您指定默认值 (2认同)
  • 另外值得注意的是,"get-in"仅适用于关联结构,所以如果你的地图中有seq,你最好使用线程宏 (2认同)