Skip to content

Instantly share code, notes, and snippets.

@Chouser
Created September 21, 2010 13:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chouser/589694 to your computer and use it in GitHub Desktop.
Save Chouser/589694 to your computer and use it in GitHub Desktop.
Avoid forcing lazy seqs when printing
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; modified by Chris Houser
(require '[clojure.contrib.reflect :as hack])
(def *print-force-lazy* false)
(defn unrealized? [x]
(and (instance? clojure.lang.LazySeq x)
(hack/get-field clojure.lang.LazySeq "fn" x)))
(defn print-lazy-sequential [^String begin, print-one, ^String sep, ^String end, sequence, ^java.io.Writer w]
(binding [*print-level* (and (not *print-dup*) *print-level* (dec *print-level*))]
(if (and *print-level* (neg? *print-level*))
(.write w "#")
(do
(.write w begin)
(if (unrealized? sequence)
(.write w "...unrealized...")
(when-let [xs (seq sequence)]
(loop [xs xs
print-length (or *print-length* 0)]
(if (and (not *print-dup*) *print-length* (zero? print-length))
(.write w "...")
(do
(print-one (first xs) w)
(if (unrealized? (rest xs))
(.write w " ...unrealized...")
(when-let [xs (next xs)]
(.write w sep)
(recur xs (dec print-length)))))))))
(.write w end)))))
(defmethod print-method clojure.lang.ISeq [o, ^java.io.Writer w]
(#'clojure.core/print-meta o w)
(if *print-force-lazy*
(#'clojure.core/print-sequential "(" #'clojure.core/pr-on " " ")" o w)
(print-lazy-sequential "(" #'clojure.core/pr-on " " ")" o w)))
(map identity '(0 1 2 3))
;=> (...unrealized...)
(next (map identity '(0 1 2 3)))
;=> (1 ...unrealized...)
(rest (map identity (vec (range 100))))
;=> (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ...unrealized...)
(def vs (map identity (vec (range 100))))
vs
;=> (...unrealized...)
(first vs)
;=> 0
vs
;=> (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ...unrealized...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment