Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I avoid evaluation of a lazy-seq inside a collection
    primarykey
    data
    text
    <p>I'm trying to write a debug macro that prints out expressions and their values. This lead to problems if I send in a lazy-seq, because if I turn it into a string (with str) the program hangs. It's easy to detect a lazy-seq if it's at the toplevel:</p> <pre><code>(def foo (cycle [1 2])) (= (type foo) clojure.lang.LazySeq) ;=&gt; true </code></pre> <p>But of course if it's nested inside another collection this doesn't work</p> <pre><code>(def bar (list (cycle [1 2]))) (= (type bar) clojure.lang.LazySeq) ;=&gt; false </code></pre> <p>To deal with this I would need one of two things:</p> <p>1: A function which checks a collection too see if it contains a lazy-seq nested somewhere.</p> <p>2: A function to turn a collection into a string without evaluating nested lazy-seqs, something like this: </p> <pre><code>(str2 {:inf (cycle [1 2])}) =&gt; "{:inf #clojure.lang.LazySeq@e9383}" </code></pre> <p>Using Michał Marczyk's answer I came up with this macro:</p> <pre><code>(defmacro dbg-print [&amp; rest] "Print out values or expressions in context" `(let [lazy-take# 5 ;when printing lazy-seq, how many elements to print symb-str# (map str '~rest) symb-evl# (reverse (binding [*print-length* 10] (loop [coll# (list ~@rest) retur# '()] (if (not (empty? coll#)) (recur (rest coll#) (cons (pr-str (first coll#)) retur#)) retur#)))) pairs# (map #(str %1 %2 %3 %4) symb-str# (repeat ":") symb-evl# (repeat " ")) str# (reduce str pairs#)] (println (format "%s\n" str#)))) </code></pre> <p>It works like this:</p> <pre><code>(dbg-print (+ 1 3) (cycle [1 2])) ;=&gt; (+ 1 3):4 (cycle [1 2]):(1 2 1 2 1 2 1 2 1 2 ...) </code></pre> <p>And can handle nested lazy-seqs:</p> <pre><code>(dbg-print (list (cycle [1 2]))) ;=&gt; (list (cycle [1 2])):((1 2 1 2 1 2 1 2 1 2 ...)) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload