开发者

get even/odd indexed elements from a Collection(List of Maps) in Clojure

开发者 https://www.devze.com 2023-03-30 08:27 出处:网络
I have a List of Map, I need to get the even/odd in开发者_如何学JAVAdexed elements from that list in Clojure.

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"­ "foob­ar" "quux­" ])
; -> {:even ["foo" "baz" "quux"], :odd ["bar" "foobar"]}
0

精彩评论

暂无评论...
验证码 换一张
取 消