clojure.set索引函数的示例用法

时间:2015-01-10 17:51:33

标签: clojure

我看了docs但是它的描述没有给出关于索引函数用法的任何提示/示例,除了以下描述。

Usage: (index xrel ks)


Returns a map of the distinct values of ks in the xrel mapped to a
set of the maps in xrel with the corresponding values of ks.

请分享index功能

的一些代码示例

1 个答案:

答案 0 :(得分:3)

examples available上有几个Grimoire。 Grimoire通常比官方Clojure文档有更广泛的例子。

(use '[clojure.set :only (index)])

;; Suppose you have a set of descriptions of the weights of animals:

user=> (def weights #{ {:name 'betsy :weight 1000}
                       {:name 'jake :weight 756}
                       {:name 'shyq :weight 1000} })


;; You want the names of all the animals that weight 1000. One way to do
;; that uses `index`. First, you can group the set elements (the maps)
;; so that those with the same weights are in the same group.

user=> (def by-weight (index weights [:weight]))
#'user/by-weight

;; index returns a map.  The keys are maps themselves, where {:weight
;; 756} and {:weight 1000} are taken from the maps in the weights set.  The
;; values in the map returned by index are sets that contain map entries
;; from the above weights set.

user=> by-weight
{{:weight 756} #{{:name jake, :weight 756}}, 
 {:weight 1000} #{{:name shyq, :weight 1000} 
                  {:name betsy, :weight 1000}}}