Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress the printing of the data an atom holds in the REPL? (or ref, agent, ...)

The following is perfectly valid Clojure code:

(def a (atom nil))
(def b (atom a))
(reset! a b)

it is even useful in situations where back references are needed.

However, it is annoying to work with such things in the REPL: the REPL will try to print the content of such references whenever you type a or b, and will, of course, generate a stack overflow error pretty quickly.

So is there any way to control/change the printing behaviour of atoms/refs/agents in Clojure? Some kind of cycle detection would be nice, but even the complete suppression of the deref'ed content would be really useful.

like image 644
amadeoh Avatar asked Jan 10 '23 23:01

amadeoh


1 Answers

You can say

(remove-method print-method clojure.lang.IDeref)

to remove special handling of derefable objects (Atoms, Refs etc.) from print-method, causing them to be printed like so:

user=> (atom 3)
#<Atom clojure.lang.Atom@5a7baa77>

Alternatively, you could add a more specific method to suppress printing of contents of some particular reference type:

(defmethod print-method clojure.lang.Atom [a ^java.io.Writer w]
  (.write w (str "#<" a ">")))

user=> (atom 3)
#<clojure.lang.Atom@4194e059>
like image 168
Michał Marczyk Avatar answered May 21 '23 12:05

Michał Marczyk