我正在使用 re-frame,并且我有一个原子绑定到我的收藏,就像这样:
my-collection (atom {:one [] :two [] :three [] :four [] :five [] :six [] :seven [] :eight []})
然后我将它发送给 assoc 到 db,稍后,我将订阅它以在这样的 doseq 中使用:
(doseq [each (:one my-collection)]
(if)
(if)
(if)
)
现在有 8 个 doseq,我想把它放在一个循环上,以避免写 8 次长 doseq。 我该怎么做?
我已经试过了,但它不起作用:
(let [parts [:one :two :three :four :five :six :seven :eight]
index (atom 0)]
(loop [each ((nth parts @index) my-collection)]
(do
(if (= :one (nth parts @index)
some code)
(if (= :four (nth parts @index)
some code)
(if (= :eight (nth parts @index)
some code)
(swap! index inc)
(recur (nth parts @index))
)
)
)
更新:
我还需要在每个 if 中使用部件中的关键字。
使用嵌套的 doseq 宏怎么样?
(doseq [part [:one :two :three :four]]
(doseq [each (get my-collection part)]
; ...
))
像这样的东西应该有用。
(def my-collection
(atom {:one [:a :b]
:two [:c :d]
:three [:e :f]
:four [:g :h]
:five [:aa :bb]
:six [:cc :dd]
:seven [:ee :ff]
:eight [:gg :hh]}))
(doseq [k [:one :two :three :four :five :six :seven :eight]
item (k @my-collection)]
;; replace this one with your business code
(printf "processing item %s from part %s\n" item k))
;; processing item :b from part :one
;; processing item :c from part :two
;; processing item :d from part :two
;; processing item :e from part :three
;; processing item :f from part :three
;; processing item :g from part :four
;; processing item :h from part :four
;; processing item :aa from part :five
;; processing item :bb from part :five
;; processing item :cc from part :six
;; processing item :dd from part :six
;; processing item :ee from part :seven
;; processing item :ff from part :seven
;; processing item :gg from part :eight
;; processing item :hh from part :eight
如果不知道
if
块中的用例,就无法真正提供准确的帮助。但是,如果迭代每个 key-value
对并应用特定代码是您的用例,那么 map
将是这里的完美选择。
具有以下收藏:
(def my-collection
(atom {:one [1]
:two [2]
:three [3]
:four [4]
:five [5]
:six [6]
:seven [7]
:eight [8]}))
你应该将你的逻辑定义为一个函数,比如:
(defn process-kv [[key value]]
;; You would probably have a `cond` with specific condition for each key.
{(name key) (apply list value)})
和
map
这个功能在你的收藏中像这样:
(map process-kv (seq @my-collection))
这将导致:
({one (1)}
{two (2)}
{three (3)}
{four (4)}
{five (5)}
{six (6)}
{seven (7)}
{eight (8)})
您可以通过在
keys
的输出中添加 keep
来进一步忽略处理未知的map
。