Clojure获取嵌套映射值

Joa*_*all 15 clojure

所以我习惯在我的应用程序中使用嵌套数组或设置图.我尝试在Clojure中设置一个像这样:

(def gridSettings
  {:width 50
   :height 50
   :ground {:variations 25}
   :water {:variations 25}
   })
Run Code Online (Sandbox Code Playgroud)

我想知道你是否知道检索嵌套值的好方法?我试着写作

(:variations (:ground gridSettings))
Run Code Online (Sandbox Code Playgroud)

哪个有效,但它是后缀并且相当繁琐,特别是如果我添加几个级别.

mty*_*aka 28

这是做什么的get-in:

(get-in gridSettings [:ground :variations])
Run Code Online (Sandbox Code Playgroud)

从文档字符串:

clojure.core/get-in
([m ks] [m ks not-found])
  Returns the value in a nested associative structure,
  where ks is a sequence of keys. Returns nil if the key
  is not present, or the not-found value if supplied.
Run Code Online (Sandbox Code Playgroud)


dby*_*rne 24

您可以使用线程优先宏:

(-> gridSettings :ground :variations)
Run Code Online (Sandbox Code Playgroud)

我喜欢->get-in除了两个特殊情况:

  • 当键是在运行时确定的任意序列时.
  • 提供未找到的值很有用.

  • 但是` - >`可以与`或`一起使用,以便很好地返回一个未找到的值.`(get-in grid-settings [:ground:variations]"not found!")`vs`( - > grid-settings:ground:variations(或"not found!"))` (4认同)
  • 整个表达式的结果只是"nil".不会抛出异常. (2认同)

Ank*_*kur 11

除了其他答案(get-in->宏)之外,有时你想从地图中获取多个值(嵌套或不嵌套),在这些情况下,解构可能真的很有帮助

(let [{{gv :variations} :ground
       {wv :variations} :water} gridSettings]
  [gv wv]) 
Run Code Online (Sandbox Code Playgroud)