【问题标题】:Idiomatic way to get from nested structures in Clojure从 Clojure 中的嵌套结构中获取的惯用方法
【发布时间】:2015-04-05 12:00:45
【问题描述】:

以下哪个是更惯用的 Clojure?

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

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

(-> book :authors first)
;; => "Michael Fogus"

当我有更复杂的数据结构时,这变得更相关。大概这两者在技术上没有区别吧?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    get-in 更适合嵌套结构,因为许多有趣的键是不可调用的,特别是向量中的索引(firstsecond 除外)或哈希映射中的字符串键。

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

    【讨论】:

    • 如果密钥不存在,您还可以指定默认值
    • 另外值得注意的是,get-in 仅适用于关联结构,因此如果您的地图中有序列,则最好使用线程宏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多