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 に答える