如何在Clojure中按值的真实性并行过滤数据?

问题描述 投票:0回答:2

我们有一些这样的数据:

(def x {:title ["NAME" "CODE" "ORDER" "MIN" "MAX" "IMG"]
        :show-in-list [true true true true false false]
        :key [:name :code :order :min :max :image]
        :input-type [:txt :txt :num :num :num :img]
        :value [nil nil nil nil nil nil]
        :required [true true false false false false]})

我们想用:required的布尔值过滤这些值,结果是:

{:title ["TITLE" "CODE"],
 :show-in-list [true true],
 :key [:part_name :part_code],
 :input-type [:txt :txt],
 :value [nil nil],
 :required [true true]}
dictionary filter clojure reduce clojurescript
2个回答
0
投票

这是一个简单明了的暴力破解尝试:

(def x ...)

(into {}
      (map
       (fn [[k vals]]
         [k (->> (map #(when %1 %2) (:required x) vals)
                 (remove nil?)
                 vec)])
       (dissoc x :required)))

这里是此概念的另一种(功能)语言实现的文档:Pick, from Mathematica


0
投票
(defn bar [state [v r]]
  (if r
    (conj state v)
    state))

(defn foo [req]
  (fn [state [k v]]
    (let [a (map #(vector %1 %2) v req)
          b (reduce bar [] a)]
      (assoc state k b))))

(reduce (foo (:required x)) {} x)
© www.soinside.com 2019 - 2024. All rights reserved.