Clojure过滤器按键图 [英] clojure filter map by keys
问题描述
我正在关注以下示例: http://groups.google.com/group/clojure/ Browse_thread / thread / 99b3d792b1d34b56
I'm following this example: http://groups.google.com/group/clojure/browse_thread/thread/99b3d792b1d34b56
(请参阅最后答复)
我得到的错误:
Clojure 1.2.1
user=> (def m {:a "x" :b "y" :c "z" :d "w"})
#'user/m
user=> (filter #(some % [:a :b]) m)
java.lang.IllegalArgumentException: Key must be integer
(user=>
我也不明白为什么这行得通,不是(某些)返回第一个匹配值 x,
Also I don't understand why this would even work. Isn't (some ...) going to return the first matching value, "x", every time? I'm a total noob at clojure and just trying to learn.
请赐教我。
推荐答案
如果您在地图上迭代,您将获得键值对而不是键。例如,
If you "iterate" over a map, you'll get key-value pairs rather than keys. For instance,
user=> (map #(str %) {:a 1, :b 2, :c 3})
("[:a 1]" "[:b 2]" "[:c 3]")
因此您的匿名函数尝试评估(某些[:a x] [:a:b])
显然不起作用。
Thus your anonymous function tries to evaluate (some [:a "x"] [:a :b])
which clearly does not work.
意识形态解决方案是使用另一个答案中提到的选择键
。
The ideomatic solution is to use select-keys
as mentioned in another answer.
这篇关于Clojure过滤器按键图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!