如何获得多方法的变量?

时间:2015-03-28 15:18:31

标签: clojure

我正在尝试使用dire向多方法添加挂钩。作者说它可能不起作用。 以下是具有正常功能的示例:

(ns mydire.prehook
  (:require [dire.core :refer [with-pre-hook!]]))

(defn times [a b]
  (* a b))

(with-pre-hook! #'times
  "An optional docstring."
  (fn [a b] (println "Logging something interesting.")))

(times 21 2) ; => "Logging something interesting."

如您所见,with-pre-hook!已通过(var times)(与#'times相同)。

问题是当为多方法调用var时,我得到一个异常: clojure.lang.PersistentList cannot be cast to clojure.lang.Symbol

有没有办法让这项工作?

以下是我的代码示例:

(defmulti get-url identity)

(defmethod get-url :stackoverflow
  [site]
  "http://stackoverflow.com")

(with-pre-hook! (var (get-method get-url :stackoverflow))
  (fn [x] (println "getting url for stackoverflow.")))

1 个答案:

答案 0 :(得分:1)

var是一个宏,它不会评估它的参数。如果你给它一个列表,它就不会评估列表,它会拒绝它,因为它是一个列表,而不是一个符号。

没有var要附加到特定方法,因为defmethod不创建var,它会修改附加到它的多方法的分派。 get-method返回的值是一个函数,而不是var。

在查看dire后,它特别需要一个var来执行,并且在没有重新设计的情况下不会对多方法的特定方法起作用。所以不,你不能在特定方法上使用with-pre-hook,尽管它可能适用于多方法本身(包括其所有方法)。