是否有一个标准的func,它接受一个dict和一个键列表并返回相应的val列表?

Jos*_*les 9 clojure

我正在寻找类似于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)

如果你想要的结果作为载体,只要使用vecinto [] ...,或更换mapmapv.

  • 换句话说(def desired-fn mapv) (3认同)

Jos*_*les 1

Jay Fields 在一篇富有洞察力的博客文章 @ http://blog.jayfields.com/2011/01/clojure-select-keys-select-values-and.html中探讨了这个函数和其他几个相关函数。

(就在几分钟前,当我搜索“选择键”时,我偶然发现了这一点。)

我仍然想知道某个地方是否有“规范”的实现,所以我将问题悬而未决。