Moving Beyond Simple Dispatch

Clojure’s print function prints various “sequencey” things as lists. If you wanted my-print to do something similar, you could add a method that dispatched on a collection interface high in the Java inheritance hierarchy, such as Collection:

 (require '[clojure.string :as str])
 (​defmethod​ my-print java.util.Collection [c]
  (.write *out* ​"("​)
  (.write *out* (str/join ​" "​ c))
  (.write *out* ​")"​))

Now, try various sequences to see that they get a nice print representation:

 (my-println (take 6 (cycle [1 2 3])))
 | (1 2 3 1 2 3)
 -> nil
 
 (my-println [1 2 3])
 | (1 2 3)
 -> nil

Perfectionist that you are, you cannot stand that vectors print with rounded braces, unlike their ...

Get Programming Clojure, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.