2014-11-02 30 views
1

我有這樣過濾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"]}) 

地圖如何過濾所以它只能說明產品id其中數量爲1個或更多?

我已經嘗試過做這樣

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

,但它不工作

回答

1

第一步是構造一對產品ID和數量:

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

第二步將過濾出哪個數量大於0,這裏我使用(Integer。xx)將數量轉換爲數字。

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

您需要創建一個函數來傳遞的第一個參數filter。其次,需要在做你可以不使用read-string比較爲1,前解析量:

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

地圖調用可能是'(地圖列表((juxt:price:quantity:productId)invoce))' – noisesmith 2014-11-02 18:33:42

+0

@noisesmith ITYM'(應用地圖列表((juxt ...)...))''。 – amalloy 2014-11-04 05:20:27

0

通常情況下,數據是比較容易處理時,它的一點點更「正常」的,所以你不必擔心像你的樣品中的索引。我建議將它存儲爲({:id x:price y:quant z} ...)的一個seq。

這個函數是:

(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 

假設你的數據集不具有否定的數量。