我正在寻找类似于select-keys的东西:
(desired-fn {:a 1, :b 2, :c 3, :d 4} [:a :d])
;= [1 4]
;; N.B. the order of the keys in the argument seq is preserved
(= (desired-fn (array-map :a 1, :b 2, :c 3, :d 4)
[:b :c])
(desired-fn (array-map :d 4, :c 3, :a 1, :b 2)
[:b :c]))
;= true
Run Code Online (Sandbox Code Playgroud)
虽然我还没有想出一个好名字,但实施起来并不是特别难:
(defn select-values-corresponding-to-keys [m ks]
(for [k ks]
(get m k)))
Run Code Online (Sandbox Code Playgroud)
我不知道满足这种需求的标准功能吗?如果没有,其他语言-eg,Python,Ruby,Haskell-是否有此功能的名称?
Joh*_*hnJ 11
地图是按键操作的功能:
({:a 1, :b 2} :a)
;=> 1
(map {:a 1, :b 2, :c 3, :d 4} [:a :d])
;=> (1 4)
(= (map (array-map :a 1, :b 2, :c 3, :d 4)
[:b :c])
(map (array-map :d 4, :c 3, :a 1, :b 2)
[:b :c]))
;=> true
Run Code Online (Sandbox Code Playgroud)
如果你想要的结果作为载体,只要使用vec或into [] ...,或更换map有mapv.
Jay Fields 在一篇富有洞察力的博客文章 @ http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html中探讨了这个函数和其他几个相关函数。
(就在几分钟前,当我搜索“选择键”时,我偶然发现了这一点。)
我仍然想知道某个地方是否有“规范”的实现,所以我将问题悬而未决。