Skip to content

Instantly share code, notes, and snippets.

@tranchis
Created October 7, 2015 14:21
Show Gist options
  • Save tranchis/595cf28bab50619dfd68 to your computer and use it in GitHub Desktop.
Save tranchis/595cf28bab50619dfd68 to your computer and use it in GitHub Desktop.
A Clojure function to obtain a lazy sequence with all the elements from an arbitrary amount of (potentially lazy!) input sequences ordered by a given function
(ns ordered-combination)
(defn ordered-combination
[sort-fn seqs]
(if (every? empty? seqs)
'()
(let [sorted (sort-by #(sort-fn (first %)) seqs)
chosen (first sorted)
new-seqs (concat [(rest chosen)] (rest sorted))]
(concat [(first chosen)]
(lazy-seq (ordered-combination sort-fn new-seqs))))))
;; Example
#_(take 1000
(ordered-combination
identity
(take 10 (repeatedly #(repeatedly (fn [] (Math/random)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment