有clojure.core/map-indexed
; 它很相似,但不完全是您要查找的内容。
例如
(map-indexed vector '[a b c]) ;=> '([0 a] [1 b] [2 c])
这非常接近我认为你想要的:
(defn map-depth
"Maps each element of s with an array of indices, as used by e.g. update-in,
optionally at the given depth"
([f s depth path]
(if (or (and depth (zero? depth))
(not (sequential? s)))
(f s path)
(map-indexed (fn [i e]
(map-depth f e
(when depth (dec depth))
(conj path i)))
s)))
([f s depth]
(map-depth f s depth []))
([f s]
(map-depth f s nil [])))
例如
(map-depth vector '[a [b c] d]) ;=> '([a [0]] ([b [1 0]] [c [1 1]]) [d [2]])
(map-depth vector '[a b c] 0) ;=> '[[a b c] []]
(map-depth vector '[[a b] [a b] [a b]] 1) ;=> '([[a b] [0]] [[a b] [1]] [[a b] [2]])
不过,您是来自 Mathematica 背景吗?
同样重要的是要记住 Clojure 的+
运算符不能很好地处理列表。
在 Mathematica 你可以做
{1, 2, 3, 4} + 2 (* -> {3 4 5 6} *)
但是 Clojure 会抱怨;你必须解决它。
(+ [1 2 3 4] 2) ;=> ClassCastException
(map (partial + 2) [1 2 3 4]) ;=> (3 4 5 6)