从Clojure中的Collection(地图列表)中获取偶数/奇数索引元素

时间:2011-08-25 06:38:50

标签: java list dictionary clojure closures

我有一个Map列表,我需要在Clojure中从该列表中获取偶数/奇数索引元素。 我不想迭代思考列表与for循环。有没有small或single_word函数?

2 个答案:

答案 0 :(得分:27)

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)

答案 1 :(得分:-1)

我不知道有任何内置功能,但是自己写一个并不简单,这是我的尝试:

(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"]}