6

関数を書いたとしましょう:

(defn foo [to x] (conj to x))

toいくつかのプロトコルを実装する必要があることを述べて、それを文書化したいと思います(構造/タイプtoが呼び出しをサポートする必要があるようにconj)。この情報を含む Web サイトまたはデータベースはありますか? 明らかに、この質問を「すべての clojure プロトコルの完全なリファレンスはどこで見つけることができますか?」に一般化したいと思います。

Sam Estep の提案を使用した明確で具体的な例として、次のようになります。

(defn invert-many-to-one
  "returns a one-to-many mapping where vals are collections of type `(constructor-fn)`,
   (defaults to `hash-set`). Note that `constructor-fn` is a function of 0 args.
  `insert-fn` function can be passed. if only `constructor-fn` is passed
  then `insert-fn` defaults to `conj` and `(constructor-fn)` must be an instance
  of `clojure.lang.IPersistentCollection`"
  ([m] (invert-many-to-one hash-set conj m))
  ([constructor-fn m] {:pre [(instance? clojure.lang.IPersistentCollection (constructor-fn))]}
   (invert-many-to-one constructor-fn conj m))
  ([constructor-fn insert-fn m]
   (persistent!
    (reduce (fn [m [k v]]
              (assoc! m v (insert-fn (clojure.core/get m v (constructor-fn)) k)))
            (transient {}) m))))
4

1 に答える 1