【问题标题】:How to bypass print-method如何绕过打印方法
【发布时间】:2017-09-08 15:09:51
【问题描述】:

我有一个应用程序,里面有很多大地图和其他东西,打印出来很难看,所以我为它们做了一个自定义打印功能,并设置print-method 来调用它,如下所示:

(defmethod print-method clojure.lang.PersistentArrayMap [v ^java.io.Writer w]
  (.write w (fstr1 v)))

fstr1内部,如果我确定地图不是需要特殊处理的类型之一,我该如何调用普通的打印方法?

This answer 建议将:type 放在元数据中,因为print-method 会派发它。我在这方面取得了一些成功,但我不能总是控制元数据,所以我希望有一种方法可以从 fstr1 中“转发”到先前定义的打印方法。


作为参考,这是我当前对fstr1 的实现:

(defn fstr1 ^String [x]
  (cond
    (ubergraph? x)
      (fstr-ubergraph x)
    (map? x)
      (case (:type x)
        :move (fstr-move x)
        :workspace "(a workspace)"
        :bdx (fstr-bdx x)
        :rxn (fstr-rxn x)
        (apply str (strip-type x)))
    :else
      (apply str (strip-type x))))

【问题讨论】:

  • 在研究替代解决方案之前 - 您是否尝试过 (set! *print-length* 10)

标签: clojure multimethod


【解决方案1】:

您可以随时重新绑定 print-object 并将真正的 print-object 收起来,以便在适当的时候调用它:

user> (let [real-print-method print-method]
        (with-redefs [print-method (fn [v w]
                                     (if (and (map? v)
                                              (:foo v))
                                       (do
                                         (real-print-method "{:foo " w)
                                         (real-print-method (:foo v) w)
                                         (real-print-method " ...}" w))
                                       (real-print-method v w)))]
          (println {:foo 42 :bar 23} {:baz 11 :quux 0})))
{:foo 42 ...} {:baz 11, :quux 0}
nil
user> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2012-06-17
    • 2017-05-08
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多