Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a good toString method for a deftype'd object in clojure

(deftype Bag [state]
   Object
     (toString [bag]
       (str "Bag???" state)))

I want the toString to look something like

clojure.core=> (def b (Bag. {:apples 1 :bannanas 4}))
#'clojure.core/b
clojure.core=> (str b)
"BAG: {:apples 1 :bannanas 4}"

What is a nice clojurey way of representing that information? Is

"Bag/{:k :v}" 

better? How does the community do you call your toStrings?

like image 342
Nick Orton Avatar asked Sep 10 '10 22:09

Nick Orton


1 Answers

The following is for deftype.

user=> (deftype Bag [state] 
         Object 
         (toString [_] 
           (str "BAG: " (pr-str state))))
user.Bag
user=> (def b (Bag. {:apples 1 :bannanas 4}))
#'user/b
user=> (str b)
"BAG: {:bannanas 4, :apples 1}"
like image 107
Alex Taggart Avatar answered Sep 28 '22 09:09

Alex Taggart