我有一个Map列表,我需要从Clojure中的列表中获得偶数/奇数索引元素。我不想用for循环来遍历列表。是否有任何小函数或单词函数?
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)
我不知道有什么内置的函数,但是自己写一个也不是那么冗长,下面是我的尝试:
(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"]}