3

この関数は機能しますが、私は Clojure を学習している最中であり、これを記述するためのより良い/よりクリーンな方法があるかどうかを知りたいです:

;; loop over methods, update the scripts map, and return scripts

(defn update-scripts
  [filename]
  (loop [scripts {}
         methods (get-methods filename)]
    (if (seq methods)
      (let [method (first methods)
            sig (get-method-signature method)
            name (get-method-name sig)]
        (recur (assoc scripts name {:sig sig, :method method})
               (rest methods)))
      scripts)))


(update-scripts "gremlin.groovy")

更新:これが私が最終的に使用したものです:

(defn- update-scripts
  [scripts method]
  (let [sig (get-method-signature method)
        name (get-method-name sig)]
    (assoc scripts name {:sig sig :method method})))

(defn get-scripts
  [filename]
  (reduce update-scripts {} (get-methods filename)))
4

3 に答える 3

4
(defn update-scripts
  [filename]
  (into {} (map (fn [m] [ (get-method-name (get-method-signature m)) {:sig (get-method-signature m), :method m}  ] ) (get-methods filename) )))
于 2012-05-10T12:40:52.890 に答える
2

次のようにreduceでこれを行います:

(defn update-scripts
  [filename]
  (reduce (fn [scripts method]
            (let [sig (get-method-signature method)
                  name (get-method-name sig)]
              (assoc scripts name {:sig sig :method method})))
          {}
          (get-methods filename)))

これは、コレクションを取得して別の型のコレクションを返す必要がある場合に従う「パターン」です。ここにメソッドのリストがあり、このリストを (何らかの処理を行った後に) マップに変換したいと考えています。reduce がこれを行うための最も読みやすい方法だと思います。

于 2012-05-10T12:23:35.847 に答える
2

mapによって返された各エントリのハッシュマップを作成し、これらすべてのハッシュマップを 1 つに構築するためにget-methods使用mergeします。

(defn update-scripts
  [filename]
  (apply merge
         (map
          #(hash-map (get-method-name %) {:sig (get-method-signature %) :method %})
          (get-methods filename))))

一般に、の代わりに などmapの標準的なシーケンス操作関数を使用することをお勧めします。filterloop

于 2012-05-10T12:40:03.327 に答える