2

我正在编写一些 Clojure 代码,其中我有一个像这样的实体树:

foo1
 +-- bar1
 | +-- baz1
 | +-- baz2
 +-- bar2
   +-- baz3
foo2
 +-- bar3
   +-- baz4

万一我荒谬的 ASCII 艺术没有意义,我有一个foos列表,每个都可以有零个或多个bar,每个可能有零个或多个bazes

我要做的是生成一个哈希映射,其中键是baz ID,值是bar ID;即上图将是:

{"baz1" "bar1", "baz2" "bar1", "baz3" "bar2", "baz4" "bar3"}

我的数据结构如下所示:

(def foos [
  {:id "foo1" :bars [
    {:id "bar1" :bazes [
      {:id "baz1"}
      {:id "baz2"}
    ]}
    {:id "bar2" :bazes [
      {:id "baz3"}
    ]}
  ]}
  {:id "foo2" :bars [
    {:id "bar3" :bazes [
      {:id "baz4"}
    ]}
  ]}
])

这是我构建 baz-to-bar 映射的代码:

(defn- baz-to-bar [foos]
  (let [b2b-list (flatten (for [f foos] (flatten (for [bar (:bars c)] (flatten (for [baz (:bazes bar)] [(:id baz) (:id bar)]))))))
        b2b-map (if (not (empty? b2b-list)) (apply hash-map b2b-list))]
    (if b2b-map [:b2b (for [baz (keys b2b-map)] (entry-tag baz (b2b-map baz)))])))

它有效,但非常迟钝。

谁能在 Clojure 中提出一种更优雅、更有希望地道的方式来做到这一点?

4

1 回答 1

6
(into {} (for [foo foos
               {bar-id :id :as bar} (:bars foo)
               {baz-id :id} (:bazes bar)]
           {baz-id bar-id}))
于 2012-06-03T21:52:12.137 回答