I'm absolutely new to Clojure (started learning it yesterday). After I went through some tutorials and checked out the basics I implemented the following Binary search algorithm:
(defn log-search [elements, elem-to-find] (loop [left 0 right (- (count elements) 1)] (when (<= left right) (def m (int (Math/floor (/ (+ left right) 2)))) (def actual (nth elements m)) (cond (= actual elem-to-find) m (< actual elem-to-find) (recur (+ m 1) right) (> actual elem-to-find) (recur left (- m 1))))))
The followings are intentional in the implementation:
- returning nil on empty sequence
- I return nil if the element is not present
- I do not care if
(+ left right)overflows on very big sequence (I'm focusing only on the language features)
- Is there any Clojure (or funcional programming) antipattern in the code?
- What would be a more functional (or Clojure) approach?
Any other suggestions are more than welcomed.