I have a List of Map, I need to get the even/odd in开发者_如何学JAVAdexed elements from that list in Clojure. I don't want to iterate thought the list with for loop. Is there any small or single_word function?
user=> (take-nth 2 [0 1 2 3 4 5 6 7 8 9])
(0 2 4 6 8)
user=> (take-nth 2 (rest [0 1 2 3 4 5 6 7 8 9]))
(1 3 5 7 9)
I do not know of any built-in function for this, but it is not that verbose to write one yourself, here is my attempt:
(defn evens-and-odds [coll]
(reduce (fn [result [k v]]
(update-in result [(if (even? k) :even :odd)] conj v))
{:even [] :odd []}
(map-indexed vector coll)))
(evens-and-odds [ "foo" "bar" "baz" "foobar" "quux" ])
; -> {:even ["foo" "baz" "quux"], :odd ["bar" "foobar"]}
精彩评论