代码之家  ›  专栏  ›  技术社区  ›  Rayne

如何使用pprint在多行上格式化地图?

  •  16
  • Rayne  · 技术社区  · 14 年前

    pprint {:a "b", :b "c", :d "e"} . 相反,我希望这样被打印,可以选择使用逗号:

    {:a "b"
     :b "c"
     :d "e"}
    

    用pprint怎么做?

    2 回复  |  直到 14 年前
        1
  •  13
  •   intuited    14 年前

    你可以设置 *print-right-margin*

    Clojure=> (binding [*print-right-margin* 7] (pprint {:a 1 :b 2 :c 3}))
    {:a 1,
     :b 2,
     :c 3}
    

    不完全是你要找的,但可能就够了?

    顺便说一句,解决这个问题或者至少我采取的方法是

    Clojure=> (use 'clojure.contrib.repl-utils)
    Clojure=> (source pprint)
    (defn pprint 
      "Pretty print object to the optional output writer. If the writer is not provided, 
    print the object to the currently bound value of *out*."
      ([object] (pprint object *out*)) 
      ([object writer]
         (with-pretty-writer writer
           (binding [*print-pretty* true]
             (write-out object))
           (if (not (= 0 (.getColumn #^PrettyWriter *out*)))
             (.write *out* (int \newline))))))
    nil
    

    嗯,嗯。。做什么 with-pretty-writer 做到 *out* ?

    Clojure=> (source clojure.contrib.pprint/with-pretty-writer)
    (defmacro #^{:private true} with-pretty-writer [base-writer & body]
      `(let [new-writer# (not (pretty-writer? ~base-writer))]
         (binding [*out* (if new-writer#
                          (make-pretty-writer ~base-writer *print-right-margin* *print-miser-width*)
                          ~base-writer)]
           ~@body
           (if new-writer# (.flush *out*)))))
    nil
    

    好吧,那么 *打印右边距* 听起来很有前途。。。

    Clojure=> (source clojure.contrib.pprint/make-pretty-writer)
    (defn- make-pretty-writer 
      "Wrap base-writer in a PrettyWriter with the specified right-margin and miser-width"
      [base-writer right-margin miser-width]
      (PrettyWriter. base-writer right-margin miser-width))
    nil
    

    此外,这是相当信息:

    Clojure=> (doc *print-right-margin*)
    -------------------------
    clojure.contrib.pprint/*print-right-margin*
    nil
      Pretty printing will try to avoid anything going beyond this column.
    Set it to nil to have pprint let the line be arbitrarily long. This will ignore all 
    non-mandatory newlines.
    nil
    

    pprint 行,你可以 proxy clojure.contrib.pprint.PrettyWriter 把它绑在 *出局*

        2
  •  6
  •   Miki Tebeka    14 年前

    我觉得你做不到,你可能需要自己写,比如:

    (defn pprint-map [m]
      (print "{")
      (doall (for [[k v] m] (println k v)))
      (print "}"))