Clojure映射是否包含级别规范



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

以下是我试图输入的内容示例:输入1:[+[[1 2][3 4 5]]2]

输出1:[[[22][34]][[54][66][78]]

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

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

象征性地:输入2:[+[a b c d e]]

输出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]]]

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]])

不过,你有数学背景吗?

还需要记住的是,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)

最新更新