【发布时间】:2017-12-28 02:26:09
【问题描述】:
假设我写了一个函数:
(defn foo [to x] (conj to x))
并希望通过声明to 必须实现某些协议来记录它(如结构/类型to 必须支持调用conj)。是否有包含此信息的网站或数据库?显然,我想将这个问题概括为“我在哪里可以找到所有 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))))
【问题讨论】:
-
老实说,我希望我能两次支持你的问题;我印象深刻。
-
你的问题比较笼统,而且你得到的答案比我五年前给出的要好,所以我不会将其作为重复项关闭,但对于 conj 来说,这一直是之前问过:stackoverflow.com/q/8781213/625403.
-
@amalloy 无论如何...接口不是协议:P
-
是的,但是“没有协议,它是一个接口”显然是同一个问题的答案。
标签: clojure protocols reference-manual