【发布时间】:2011-11-03 09:42:30
【问题描述】:
我有一个 Map 列表,我需要从 Clojure 中的该列表中获取偶数/奇数索引元素。 我不想用 for 循环迭代思想列表。有什么small或者single_word函数吗?
【问题讨论】:
标签: java list dictionary clojure closures
我有一个 Map 列表,我需要从 Clojure 中的该列表中获取偶数/奇数索引元素。 我不想用 for 循环迭代思想列表。有什么small或者single_word函数吗?
【问题讨论】:
标签: java list dictionary clojure closures
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"]}
【讨论】: