On 8 December 2011 01:51, Andy Fingerhut <andy.finger...@gmail.com> wrote: > I've been going through the PLEAC web site, writing Clojure examples > corresponding to the Perl code examples from the Perl Cookbook: > > http://pleac.sourceforge.net > > Michael Bacarella started a github repo to collect these together, and I'm > helping flesh some of them out. > > https://github.com/mbacarella/pleac-clojure > > One thing that is very convenient in Perl is doing sorts on multiple > comparison keys -- since 0 is treated as logically false in Perl, they can > simply do what in Clojure would look like: > > (sort #(or (compare (key1 %1) (key2 %2)) > (compare (key2 %1) (key2 %2)) > ...) > collection)
You can take advantage of the fact that Clojure already knows how to compare vectors. If key1, key2, ... are functions (or keywords, which act as functions on a map), you have: (sort-by (juxt key1 key2) collection) To sort a collection of maps whose keys aren't keywords, you have to work a little harder: (sort-by (fn [m] (vec (map #(get m %) [key1 key2]))) collection) These examples are easily extended to handle an arbitrary number of keys. -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en