在Clojure中过滤

时间:2014-11-02 17:31:36

标签: filter clojure

我有这样的地图

(def invoice 
{:productId ["001" "002" "003" "004" "005" "006" "007" "008" "009" "010"],
:price ["50" "60" "70" "50" "40" "45" "55" "90" "50" "70"],
:quantity ["0" "0" "1" "2" "0" "0" "0" "0" "0" "1"]})

如何过滤以便只显示数量为1或更多的产品ID?

我已经尝试过这样做了

(filter (> (invoice :quantity %) 1) (map list (invoice :price) (invoice :quantity) (invoice :productid))

但它不起作用

3 个答案:

答案 0 :(得分:2)

您需要创建一个函数作为第一个参数传递给filter。其次,您需要在比较之前解析数量,然后使用read-string进行比较:

(filter #(> (read-string (second %)) 1) (map list (invoice :price) (invoice :quantity) (invoice :productId)))

答案 1 :(得分:1)

第一步是构建一对产品ID和数量:

(map vector (invoice :quantity) (invoice :productId))
;; ["0" "001"] .... first element would be quantity and second is productiID

第二步将过滤掉哪个数量大于0,这里我使用(整数.xx)将数量转换为数字。

(filter #(> (Integer. (first %)) 0) (map vector (invoice :quantity) (invoice :productId)))

答案 2 :(得分:0)

通常情况下,当数据更加正常时,数据会更容易处理。所以你不必担心样本中的指数。我建议将其存储为({:id x:price y:quant z} ...)的序列。

这个功能可以:

(defn invoices [invoice]
  (map (fn [id price quant]
          {:id id
           :price price
           :quant quant})  (:prouctId invoice)
                           (:price invoice)
                           (:quantity invoice))

然后从那里你可以简单地

(->> invoice 
     invoices 
     (remove #(= "0" (:price %))  ;; remove "0" prices
     (map :id))) ;; get ids

假设您的数据集没有负数。