在clojure中,我如何需要多方法?

Zub*_*air 4 clojure

我知道我可以做(:use function)但我怎么做这个多方法呢?

rae*_*aek 7

其他名称空间使用多种方法的方式与函数相同.

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

(ns com.example.foo)

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

(defmulti m first)

(defmethod m :a [coll]
  (map inc (rest coll)))
Run Code Online (Sandbox Code Playgroud)

在文件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)))
Run Code Online (Sandbox Code Playgroud)

我希望这回答了你的问题!