From 1c7614dc8b639477126f33769fd3adc901c9e3c4 Mon Sep 17 00:00:00 2001 From: dwiechert Date: Fri, 26 Aug 2016 06:19:13 -0500 Subject: [PATCH] Fixed index-of for clojure. --- src/main/clojure/lists/ClojureLists.clj | 19 ++++++++----------- src/test/clojure/lists/ClojureListsTest.clj | 20 ++++++++++---------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/src/main/clojure/lists/ClojureLists.clj b/src/main/clojure/lists/ClojureLists.clj index 39628d6..8d25e39 100644 --- a/src/main/clojure/lists/ClojureLists.clj +++ b/src/main/clojure/lists/ClojureLists.clj @@ -2,7 +2,6 @@ (:require [clojure.core]) (:gen-class)) - (defn my-sum [& args] (reduce + args)) @@ -18,14 +17,12 @@ (defn exists [e elements] (> (my-count e elements) 0)) -; Currentlu this doesn't work, but should try to figure it out -;(defn- index-of-with-index -; ([e i] (do (println e i) -1)) -; ([e i x] (do (println e i x) (if (= e x) i -1))) -; ([e i x & more] (do (println e i x more) (if (= e x) i (index-of-with-index e (+ i 1) more))))) -; -;(defn index-of [e & args] -; (index-of-with-index e 0 args)) +(defn- index-of-with-index [e i elements] + (if (empty? elements) + -1 + (if (= e (first elements)) + i + (index-of-with-index e (+ 1 i) (rest elements))))) -(defn index-of2 [e & more] - (.indexOf more e)) \ No newline at end of file +(defn index-of [e elements] + (index-of-with-index e 0 elements)) \ No newline at end of file diff --git a/src/test/clojure/lists/ClojureListsTest.clj b/src/test/clojure/lists/ClojureListsTest.clj index 9b4be46..fa64060 100644 --- a/src/test/clojure/lists/ClojureListsTest.clj +++ b/src/test/clojure/lists/ClojureListsTest.clj @@ -10,6 +10,14 @@ (testing "my-max" (is (= 3 (my-max 1 2 3))))) +(deftest my-count-found + (testing "my-count-found" + (is (= 2 (my-count "a" (seq ["a" "a" "b"])))))) + +(deftest my-count-not-found + (testing "my-count-not-found" + (is (= 0 (my-count 4 (seq [1 2 3])))))) + (deftest exists-true (testing "exists-true" (is (exists "a" (seq ["b" "b" "a"]))))) @@ -20,16 +28,8 @@ (deftest index-of-found (testing "index-of-found" - (is (= 1 (index-of2 "b" "a" "b"))))) + (is (= 3 (index-of "d" (seq ["a" "b" "c" "d"])))))) (deftest index-of-not-found (testing "index-of-not-found" - (is (= -1 (index-of2 4 1 2 3))))) - -(deftest my-count-found - (testing "my-count-found" - (is (= 2 (my-count "a" (seq ["a" "a" "b"])))))) - -(deftest my-count-not-found - (testing "my-count-not-found" - (is (= 0 (my-count 4 (seq [1 2 3])))))) \ No newline at end of file + (is (= -1 (index-of "e" (seq ["a" "b" "c" "d"])))))) \ No newline at end of file