在Clojure中,我如何引用一个多方法?

5

我知道我可以使用(:use function),但是如何在多方法中执行此操作呢?

1个回答

8

多方法与函数的使用方式相同,可以从其他命名空间中调用。

如果你在com/example/foo.clj文件中有以下内容

(ns com.example.foo)

(defn f [x]
  (* x x))

(defmulti m first)

(defmethod m :a [coll]
  (map inc (rest coll)))

在文件com/example/bar.clj中,您可以以相同的方式使用f和m:
(ns com.example.bar
  (:use [com.example.foo :only [f m]]))

(defn g []
  (println (f 5)) ; Call the function
  (println (m [:a 1 2 3]))) ; Call the multimethod

;; You can also define new cases for the multimethod defined in foo
;; which are then available everywhere m is
(defmethod m :b [coll]
  (map dec (rest coll)))

我希望这可以回答你的问题!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接