我还没有找到太多的文档或编码示例来对map的向量进行操作。例如,如果我有
(def student-grades
[{:name "Billy" :test1 74 :test2 93 :test3 89}
{:name "Miguel" :test1 57 :test2 79 :test3 85}
{:name "Sandy" :test1 86 :test2 97 :test3 99}
{:name "Dhruv" :test1 84 :test2 89 :test3 94}])
我想为测试平均值添加或关联一个新的键值对,我应该了解哪些函数?另外,如果有人知道Clojure中地图矢量的任何参考/资源,请分享!非常感谢!
发布于 2011-08-14 00:30:14
在本例中,您希望为集合中的每个元素(恰好是一个映射--不幸的命名冲突)生成一个新的映射,其中包含旧映射的所有键-值对,外加一个新的键,比如:avg。对于集合中的一个函数,您希望生成一个(恰好是一个向量)。
例如:
(into [] ; optional -- places the answer into another vector
(map ; apply the given function to every element in the collection
(fn [sg] ; the function takes a student-grade
(assoc sg ; and with this student-grade, creates a new mapping
:avg ; with an added key called :avg
(/ (+ (:test1 sg) (:test2 sg) (:test3 sg)) 3.0)))
student-grades ; and the function is applied to your student-grades vector
))
Clojure ps你可以使用(doc fn-)来获取相关文档;如果你刚接触Clojure,我建议你在irc.freenode.net #clojure上与友好的朋友们一起闲逛,看看书--我目前最喜欢的是Programming Clojure,但我正在屏息等待O‘’Reilly即将出版的Clojure书。
发布于 2011-08-15 21:06:01
Hircus已经提供了一个很好的答案,但这里有另一个实现进行比较:
(defn average [nums]
(double (/ (apply + nums) (count nums))))
(map
#(assoc % :avg (average ((juxt :test1 :test2 :test3) %)))
student-grades)
=> ({:avg 85.33333333333333, :name "Billy", :test1 74, :test2 93, :test3 89} etc....)
注意事项:
对于从
中提取特定组件值列表而言,将诸如"average“之类的通用功能分离到一个单独的、命名良好的地图中通常是一个非常有用的函数
https://stackoverflow.com/questions/7051643
复制相似问题