Alan Malloy <a...@malloys.org> writes:

Hi Andy & Alan,

> This should be a function, not a macro. In fact it is just:
>
> (defn multicmp [& xs] (first (remove zero? xs)))
>
> But what you really wanted to begin with is a comparator function, so
> more like:
>
> (defn multicmp [& keys]
>   (fn [a b]
>     (or (first (remove zero? (map #(compare (% a) (% b))
>                                   keys)))
>         0)))
>
> (sort-by (multicmp < =) coll)

Nice.  I have a very similar function in my pocket, because I frequently
have to sort seqs of tuples (vectors).  That's what I came up with:

--8<---------------cut here---------------start------------->8---
(defn seq-compare
  "Returns a sequence comparator function that compares 2 sequences element by
  element according to the given comparators `cmps', i.e., the first 2 elements
  are compared with the first comparator, the second 2 elements with the second
  comparator, and so on.  Evaluates only as many comparators as are needed to
  distinguish the sequences, i.e., evaluates the comparators until one returns
  non-zero.

  `cmps' must be comparator functions that get 2 elements and returns 0, if the
  elements are equal, a negative integer, if the first is \"smaller\", or a
  positive integer, if the second is \"smaller\".

  If all comparators evaluate to 0, then the hash-codes are used as a last
  resort.

  Example: Sort a seq of 3-tuples of form [number number string] with
  descending order of the first component, ascending order of second component,
  and ascending orded of third components.  Clearly, for numbers - is a valid
  comparator, and for the strings we use compare which sorts lexicographically.

    (sort (seq-compare #(- %2 %1) - compare)
          [[1 10 \"b\"] [3 7 \"b\"] [1 2 \"b\"] [1 10 \"c\"] [3.0 17 \"a\"]])
    ;=> ([3 7 \"b\"] [3.0 17 \"a\"] [1 2 \"b\"] [1 10 \"b\"] [1 10 \"c\"])"
  [& cmps]
  (fn [a b]
    (or (first (remove zero? (map #(%1 %2 %3) cmps a b)))
        (- (hash a) (hash b)))))
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo

-- 
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

Reply via email to