我正在编写一个clojure函数来将各种数据类型格式化为字符串.
我天真的解决方案:
(defn p [d]
(cond
(vector? d) (str "vector: " d)
(list? d) (str "list: " d)))
#'user/p
user> (p [1 2 3])
"vector: [1 2 3]"
user> (p '(1 2 3))
"list: (1 2 3)"
Run Code Online (Sandbox Code Playgroud)
我之前没有使用过多种方法.我这很好用,还是有另一种方法来避免使用cond的臭味?
我将根据@rodnaph的建议,定义格式协议并将其扩展到您需要的类型:
(defprotocol Format
(fmt [this]))
(extend-protocol Format
clojure.lang.IPersistentVector
(fmt [this] (str "vector:" this))
clojure.lang.IPersistentList
(fmt [this] (str "list:" this)))
Run Code Online (Sandbox Code Playgroud)
但是我不知道哪个会有更好的性能,多方法或协议扩展.
多方法定义可能如下所示:
(defmulti fmt class)
(defmethod fmt
clojure.lang.IPersistentVector [this]
(str "vector:" this))
(defmethod fmt
clojure.lang.IPersistentList [this]
(str "list:" this))
Run Code Online (Sandbox Code Playgroud)
编辑:您可能想要检查有关协议与多方法的问题,因为很好地解释了两者的常见用例.根据该信息,最好在您的方案中使用协议.