What's wrong with just using (reverse (sort-by foo my-map))?
When you need a seq view, you can wrap it in reverse. When you don't,
the sort order is irrelevant anyway. (For a reverse-sorted seq of just
the keys, (reverse (sort-by foo (keys my-map))) works of course.)
Note that sorting a map sorts by keys; if the map is persons to
something else (e.g. account details or something) then you can sort
it by last name, or if the keys are things like {:first-name "foo"
:last-name "bar"} and the values are whole persons, but if you're
trying to sort on a field of the values that isn't a field of the
keys, you've got bigger problems than reversing the sort order.
> I'm trying to figure out how to use sort-by in reverse order.
I tend to do this:
(sort-by :foo #(compare %2 %1) coll)
> (sort-by :last-name #(compare %2 %1) persons)
>
>
> Actually having put forward that second example there I'm not sure how
> it actually works. The docs suggest that the 2nd parameter needs to
> implement Comparator (peeking at the source confirms this) but compare
> returns back a number. It is possible this might be just working by
> accident.
For convenience all Clojure fns implement Comparator (as well as
Callable and Runnable). Documented here:
So for the case I had that method worked. I wonder though if I had wanted to sort by multiple keys, with some of the keys sorting in reverse order and others in regular order, how I could do that... Say last name ascending, date of birth descending for example.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@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+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
Write your own compare function which does that. For example, for the
general case:
(def asc compare)
(def desc #(compare %2 %1))
(defn compare-by [[k comp & more] x y]
(let [result (comp (k x) (k y))]
(if (and (zero? result) (seq more))
(recur more x y)
result)))
(sort #(compare-by [:last-name asc, :date-of-birth desc] %1 %2) coll)
+1
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@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+u...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/clojure/769d3b44-e1dc-43f4-8728-7ecfdce86e79n%40googlegroups.com.