set / project不能保持顺序,如下所示:
(project (map #(hash-map :number % :square (* % %)) (range 100)) #{:square})
在保持秩序的同时使用它是否有惯用的方法,或者我必须明确添加序数并在之后对它们进行排序?
答案 0 :(得分:2)
clojure.set/project
的来源:
(defn project
"Returns a rel of the elements of xrel with only the keys in ks"
{:added "1.0"}
[xrel ks]
(set (map #(select-keys % ks) xrel)))
您需要实现自己的project
而不将结果转换为set
(defn my-project [xrel ks]
(map #(select-keys % ks) xrel))
测试:
(my-project (map #(hash-map :number % :square %)
(range 100))
#{:square})
=> ({:square 0}
{:square 1}
{:square 2}
{:square 3}
...
{:square 99})
<强>更新即可。另一个版本:
(defn my-project2 [xrel ks]
(map (fn [m] (into {} (filter #(ks (key %)) m)))
xrel))