Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the "middle element" from a vector in Clojure

Tags:

clojure

Simple newbie question in Clojure...

If I have an odd number of elements in a Clojure vector, how can I extract the "middle" value? I've been looking at this for a while and can't work out how to do it!

Some examples:

  • (middle-value [0]) should return [0]
  • (middle-value [0 1 2]) should return [1]
  • (middle-value [0 1 :abc 3 4]) should return [:abc]
  • (middle-value [0 1 2 "test" 4 5 6]) should return ["test"]
like image 921
monch1962 Avatar asked Dec 11 '22 16:12

monch1962


1 Answers

How about calculating the middle index and accessing by it?

(defn middle-value [vect]
  (when-not (empty? vect)
    (vect (quot (count vect) 2))))
like image 101
bereal Avatar answered Jan 22 '23 15:01

bereal