0

在尝试编写将函数(即 inc、dec 等)应用于输入向量的元素的映射函数时。输出是一个向量,函数应用于每个元素和一个索引元素。

这是我尝试输入的示例:输入 1:[+ [[1 2] [3 4 5]] 2]

输出1:[[2 2] [3 4]] [[5 4] [6 6] [7 8]]]

输入 2:[+ [1 2 3 4 5]]

输出 2:[[2] [4] [6] [8] [10]]

象征性地:输入 2:[+ [abcde]]

输出 2:[[1+a] [2+b] [3+c] [4+d] [5+e]]

输入 3:[加号,[[[[[1]]]]]]

输出 3:[[[[[[1+1]]]]] (会输出 2 但我写出了操作)

输入4:[加[[[[[1]]]]] 2]\

输出 4:[[1+[[[1]]]+[1 1]]]

4

1 回答 1

1

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)
于 2013-11-21T21:41:46.280 回答