我正在使用reframe,我有一个绑定原子到我的集合,像这样:
my-collection (atom {:one [] :two [] :three [] :four [] :five [] :six [] :seven [] :eight []})
然后我将它分派给关联数据库,然后,我将订阅它以在这样的剂量中使用:
(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中使用关键字from parts。
如何使用嵌套的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 %sn" 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)})
通过在map
的输出中添加keep
,您可以进一步忽略处理集合中未知的keys
。