Skip to content

Instantly share code, notes, and snippets.

@alexpw
Created December 21, 2012 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpw/4349972 to your computer and use it in GitHub Desktop.
Save alexpw/4349972 to your computer and use it in GitHub Desktop.
(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