我很难让Clojure中的多方法像我所期望的那样工作。我的代码的精馏如下。
(defn commandType [_ command] (:command-type command))
(defmulti testMulti commandType)
(defmethod testMulti :one [game command] (str "blah"))
(defmethod testMulti :default [& args] "Cannot understand")
(testMulti "something" {:command-type :one})
(commandType "something" {:command-type :one})现在,我希望在这里使用commandType方法调用参数,该参数当然会返回:一个应该将其发送给第一个defmethod的方法,但是我得到一个空指针异常。即使是我能想到的对multimethod的最简单调用,也给出了一个空指针:
(defmulti simpleMulti :key)
(defmethod simpleMulti "basic" [params] "basic value")
(simpleMulti {:key "basic"})然而,位于这里的clojure文档中的示例工作得很好。我是不是做错了什么基本的事?
发布于 2014-05-17 18:28:57
据我所知,它起作用了。
给定的
(defmulti testMulti (fn [_ command] (:command-type command)))
(defmethod testMulti :one [game command] (str "blah"))
(defmethod testMulti :default [& args] "Cannot understand")然后
(testMulti "something" {:command-type :one})
; "blah"
(testMulti "something" {:command-type :two})
; "Cannot understand"
(testMulti "something" 5)
; "Cannot understand"如预期的那样。
在重新运行上述程序之前,我会重置REPL。
这个简单的例子也很管用。给定的
(defmulti simpleMulti :key)
(defmethod simpleMulti "basic" [params] "basic value")然后
(simpleMulti {:key "basic"})
; "basic value"https://stackoverflow.com/questions/23714622
复制相似问题