Clojure 将函数应用于序列的每个第n个元素的简洁方法?

Clojure 将函数应用于序列的每个第n个元素的简洁方法?,clojure,functional-programming,Clojure,Functional Programming,将函数映射到序列中的每个第n个元素的简洁方法是什么?类似于(映射每n个fn coll n),这样它将只返回每n个元素转换后的原始序列,例如(映射每n个inc(范围16)4)将返回(0 1 2 4 4 5 6 8 9 10 12 13 14 16)尝试以下操作: (defn map-every-nth [f coll n] (map-indexed #(if (zero? (mod (inc %1) n)) (f %2) %2) coll)) (map-every-nth inc (rang

将函数映射到序列中的每个第n个元素的简洁方法是什么?类似于
(映射每n个fn coll n)
,这样它将只返回每n个元素转换后的原始序列,例如(映射每n个inc(范围16)4)将返回(0 1 2 4 4 5 6 8 9 10 12 13 14 16)

尝试以下操作:

(defn map-every-nth [f coll n]
  (map-indexed #(if (zero? (mod (inc %1) n)) (f %2) %2) coll))

(map-every-nth inc (range 16) 4)
> (0 1 2 4 4 5 6 8 8 9 10 12 12 13 14 16)

我建议这比公认的答案更简单、更清晰:

(defn map-every-nth [f coll n]
  (map f (take-nth n coll)))

这是一个方便的方法:

我个人更喜欢这个解决方案:

(defn apply-to-last [f col] (concat (butlast col) (list (f (last col)))))
(apply concat (map #(apply-to-last (fn [x] (* 2 x)) %) (partition 4 (range 16))))
或者作为一种功能:

(defn apply-to-last [f col] (concat (butlast col) (list (f (last col)))))
(defn map-every-nth [f col n] (apply concat (map #(apply-to-last f %) (partition n col))))
(map-every-nth (fn [x] (* 2 (inc x))) (range 16) 4)
; output: (0 1 2 8 4 5 6 16 8 9 10 24 12 13 14 32)
请注意,这很容易导致
应用于第一个
应用于第二个
应用于第三个
的功能,从而能够控制每n个元素映射的“开始”


我不知道我上面写的代码的性能如何,但对我来说,它确实更为惯用。

谢谢,我意识到它是多么微不足道,在发布它之后不久我就意识到了我是如何做到的!差不多!这只会返回coll的第n个成员,而我要求通过f映射每n个coll的整个coll,因此:(defn map every nth[f coll n](mapcat cons(map f(take nth n coll))(map rest(partition n coll))=>(map every nth inc(range 16)4)(1 1 2 3 5 6 7 9 10 11 13 14 15);干杯你的选择会带来一个好的解决方案!哎呀!刚刚注意到我是一个元素…哦!取n,从零开始…不是我期望的,但原理是一样的,我明白了。。。对不起,这个答案不是你想要的。