Created
December 21, 2012 01:02
-
-
Save alexpw/4349972 to your computer and use it in GitHub Desktop.
Example code for https://groups.google.com/d/topic/clojure/pRla3_7vqvc/discussion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(def animals [{:name "Betsy" :type :cow} | |
{:name "Murmur" :type :cat} | |
{:name "Lessie" :type :dog} | |
{:name "Dingo" :type :dog} | |
{:name "Rosie" :type :cat} | |
{:name "Rex" :type :dog} | |
{:name "Alf" :type :cat}]) | |
(def group-by-uc-name (group-by-with #(conj (or % []) (.toUpperCase (:name %2))))) | |
(group-by-uc-name :type animals) | |
=> {:cow ["BETSY"] | |
:cat ["MURMUR" "ROSIE" "ALF"] | |
:dog ["LESSIE" "DINGO" "REX"]} | |
;; now we can use this custom grouping fn to build an indexing fn to handle more than one keyword for grouping. | |
(def animals [{:name "Betsy" :type :cow :sex :female} | |
{:name "Murmur" :type :cat :sex :male} | |
{:name "Lessie" :type :dog :sex :female} | |
{:name "Dingo" :type :dog :sex :male} | |
{:name "Rosie" :type :cat :sex :female} | |
{:name "Rex" :type :dog :sex :male} | |
{:name "Alf" :type :cat :sex :male}]) | |
(def indexed-by-uc-name (index-by-with group-by-uc-name)) | |
(indexed-by-uc-name animals :type :sex) | |
=> {:cow {:female ["BETSY"]} | |
:cat {:male ["MURMUR" "ALF"] | |
:female ["ROSIE"]} | |
:dog {:male ["DINGO" "REX"] | |
:female ["LESSIE"]}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment