Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic way to iterate through all pairs of a collection in Clojure

Given a collection I want to iterate through all pairs in a collection. Example

(all-pairs seq)

(all-pairs '(a b c d)) => ([a b] [a c] [a d] [b c] [b d] [c d]))

Here is my idea

(defn all-pairs [coll]
  (for [ [idx elmt] (indexed coll)
         other-elmt (subvec coll (inc idx))]
     (vector elmt other-elm)))

But it doesn't feel idiomatic

like image 942
Frank Avatar asked Oct 29 '10 16:10

Frank


1 Answers

How about:

(use 'clojure.contrib.combinatorics)
(vec (map vec (combinations '(a b c d) 2)))
like image 113
Thomas Wagner Avatar answered Nov 08 '22 12:11

Thomas Wagner