是否有类似mapcdr函数的东西?

时间:2015-03-08 16:05:14

标签: clojure

Clojure的map是其他lisps可能会调用mapcar,而car大致相当于clojure的first。这让我想知道是否有mapcdr以及clojure是否具有cdr大致相当于clojure' s rest的函数。

我想这样的行为是这样的:

(mapcdr #(apply + %) [1 2 3 4 5])
=> (15 14 12 9 5)

扩张看起来像:

(list (apply + [1 2 3 4 5])
      (apply + [2 3 4 5])
      (apply + [3 4 5])
      (apply + [4 5])
      (apply + [5])

2 个答案:

答案 0 :(得分:1)

写了一些快速的东西,虽然它仍然很好有一些更原生的东西。

(defn maplist
  "Based on Common Lisp's maplist."
  [fn coll]
  (if (empty? coll) nil
      (cons (fn coll)
            (maplist fn (rest coll)))))

(maplist #(apply + %) [1 2 3 4 5])
=> (15 14 12 9 5)

如果没有,我会感到惊讶,因为似乎标准mapmaplist first缠绕coll

答案 1 :(得分:0)

您可以使用fn reductions,它几​​乎可以满足您的需求:

(->> [1 2 3 4 5]
     reverse
     (reductions +)
     reverse)