From b70cba0c656586836a3c951079012cd9d371fa40 Mon Sep 17 00:00:00 2001 From: Aaron Bedra and Stuart Halloway Date: Sun, 23 Aug 2009 15:01:31 -0400 Subject: add seq-utils/positions --- src/clojure/contrib/seq_utils.clj | 18 ++++++++++++++++++ src/clojure/contrib/test_contrib.clj | 3 ++- src/clojure/contrib/test_contrib/seq_utils_test.clj | 14 ++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/clojure/contrib/test_contrib/seq_utils_test.clj diff --git a/src/clojure/contrib/seq_utils.clj b/src/clojure/contrib/seq_utils.clj index d4c29c46..5f3b7446 100644 --- a/src/clojure/contrib/seq_utils.clj +++ b/src/clojure/contrib/seq_utils.clj @@ -211,3 +211,21 @@ (cons (if (identical? x NIL) nil x) (drain)))))))))) +(defmulti positions + "Returns a lazy sequence containing the positions at which item + is found in coll. Functions (responding true to fn?) are called + against members of the collection, other items are compared for + equality." + { :arglists '([item-or-pred coll]) } + (fn [item-or-pred _] + (if (fn? item-or-pred) :pred :item))) + +(defmethod positions :pred [pred coll] + (for [[idx elt] (indexed coll) :when (pred elt)] idx)) + +(defmethod positions :item [item coll] + (for [[idx elt] (indexed coll) :when (= item elt)] idx)) + + + + diff --git a/src/clojure/contrib/test_contrib.clj b/src/clojure/contrib/test_contrib.clj index 13498076..8402b7ba 100644 --- a/src/clojure/contrib/test_contrib.clj +++ b/src/clojure/contrib/test_contrib.clj @@ -20,7 +20,8 @@ [:complex-numbers :fnmap :macro-utils :monads :pprint.pretty :pprint.cl-format :str-utils :shell-out :test-graph :test-dataflow :test-java-utils :test-lazy-seqs - :test-trace :test-jmx :java-utils :expect-test :expect-test.test-adapter-test]) + :test-trace :test-jmx :java-utils :expect-test :expect-test.test-adapter-test + :seq-utils-test]) (def test-namespaces (map #(symbol (str "clojure.contrib.test-contrib." (name %))) diff --git a/src/clojure/contrib/test_contrib/seq_utils_test.clj b/src/clojure/contrib/test_contrib/seq_utils_test.clj new file mode 100644 index 00000000..1de61cb5 --- /dev/null +++ b/src/clojure/contrib/test_contrib/seq_utils_test.clj @@ -0,0 +1,14 @@ +(ns clojure.contrib.test-contrib.seq-utils-test + (:use clojure.test + clojure.contrib.seq-utils)) + + +(deftest test-positions + (are [expected pred coll] (= expected (positions pred coll)) + [1] nil [0 nil 5] + [1] nil? [0 nil 5] + () string? [:a :b :c] + [2] string? [:a :b "c"] + () :d [:a :b :c] + [0 2] :d [:d :a :d :a])) + \ No newline at end of file -- cgit v1.2.3-18-g5258