【问题标题】:Creating a collection of multiple same-depth values in a nested hashmap在嵌套哈希图中创建多个相同深度值的集合
【发布时间】:2014-06-05 23:18:11
【问题描述】:

这是一个名为 args 的假设 hashmap:

{:body {:milestones [{:status 1 :otherValues x} 
                     {:status 2 :otherValues z} 
                     {:status 1 :otherValues y]}}

我的目标是收集每个 :status 键的值。它们都是 :milestones 的子节点。

我快到了。我知道如何通过这样做来检索第一个状态的值:

(let [{[{:keys [status]} x] :milestones} :body} args]
  (println status))

最远的目标是找出哪些地图包含一个值为 1 的 :status 并为每个单独的地图创建一个新集合。

其实际应用是连接到 TeamworkPM 并使用 Google 日历同步具有“迟到”或“未完成”状态的里程碑。

在这种情况下,所需的输出将是 {1, 2, 1}。最终目标是拥有

 {{:status 1 :otherValues x} 
  {:status 1 :otherValues Y}}

【问题讨论】:

  • 你能给我们一个你想要的输出的例子吗?

标签: map clojure hashmap destructuring


【解决方案1】:

虽然我不知道如何直接将map的向量解构为变量, 相反,您可以先获取:milestones 的孩子,然后使用基本的mapfilter

请注意,您可以通过将 map 应用为函数来获取它的值。 (例如,如果 m{:key1 "val1"}(m :key1) 将是 "val1"

(def args {:body {:milestones [{:status 1 :otherValues 'x}
                               {:status 2 :otherValues 'z}
                               {:status 1 :otherValues 'y}]}})

(let [{{x :milestones} :body} args,
        y (map #(% :status) x),
        z (filter #(= (% :status) 1) x)
      ]
      (println x) ; [{:status 1, :otherValues x} {:status 2, :otherValues z} {:status 1, :otherValues y}]
      (println y) ; (1 2 1)
      (println z) ; ({:status 1, :otherValues x} {:status 1, :otherValues y})
  )

【讨论】:

  • 哇,这太不可思议了。我的心为[a(回答问题)b(显示得很好)c(显示3个不同的输出)]而感动。
  • #(% :status) 只是写 :status 的一种奇怪方式(至少在应用于地图 arg 时)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 2014-03-02
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多