2015-08-18 54 views
0

說我有地圖的列表看起來像以下:過濾圖的列表Clojure中具有潛在不同的密鑰

(def my-map '({:some-key {:another-key "val"} 
    :id "123"} 
{:some-key {:another-key "val"} 
    :id "456"} 
{:some-other-key {:a-different-key "val2"} 
    :id "789"}) 

在我試圖通過:another-key過濾這張圖,我嘗試這樣做:

(filter #(= "val" ((% :some-key) :another-key)) my-map)))

但是,這將引發在地圖上的條目不包含我篩選鍵上的NullPointerException。過濾此映射的最佳方法是什麼?排除與完全不匹配過濾模式的條目?

回答

2

如果地圖關鍵字不在地圖中,您將首先查找關鍵碼:some-key將返回nil。調用nil將導致您看到的NPE。

解決辦法很簡單,只需要把關鍵字查找自身在地圖上,即使給出一個零,其工作:

(def my-map '({:some-key {:another-key "val"} 
       :id "123"} 
       {:some-key {:another-key "val"} 
       :id "456"} 
       {:some-other-key {:a-different-key "val2"} 
       :id "789"})) 

(filter #(= "val" (:another-key (% :some-key))) my-map) 

您還可以使用get-in

(filter #(= "val" (get-in % [:some-key :another-key])) my-map) 

如果你的列表可能有nil項目:

(filter #(= "val" (:another-key (:some-key %))) my-map) 

說明離子:

(:k nil);; => nil 
(nil :k);; => NPE 
({:k 4} :k);; => 4 
(:k {:k 4});; => 4 
;; BTW, you can also specify the "not found" case: 
(:k nil :not-there);; => :not-there 

另請參閱clojure style guide

+0

太好了,非常感謝! –

相關問題