Wednesday, April 15, 2009

Sorting the list of sequences using max-key

(max-key k x y)

max-key applies the k function (which should return integer) to the rest of the arguments and returns the argument which yields the greatest number. This can be used to bubble the largest sequence to the front.

(max-key count #{1 2 3} #{4 5})
=> #{1 2 3}

(max-key count #{1 2 3} #{4 5 6 7})
=> #{4 5 6 7}

(apply max-key count '(#{3 4 5} #{1 2} #{3}))
=> #{3 4 5}

Following function takes a list of sequences and return them in the order of their size. So the sequence with most number of elements are returned first.

(defn sort-seqs [seqs]
(lazy-seq
(when-not (empty? seqs)
(let [largest-seq (apply max-key count seqs)]
(cons largest-seq (sort-seqs (remove #(identical? largest-seq %) seqs)))))))

(sort-seqs '(#{3} #{3 4 5} #{1 2}))
=> (#{3 4 5} #{1 2} #{3})

(sort-seqs '([1 2] [3] [4 5 6 7]))
=> ([4 5 6 7] [1 2] [3])

(sort-seqs '({:a 1} {a 2 :b 4} {:c 5}))
=> ({a 2, :b 4} {:c 5} {:a 1})

1 comment: