Mutually referring deftypes in Clojure
Asked Answered
P

1

7

I want to implement transient and persistent! in my Clojure deftype. As far as I can tell, this means having another deftype, TransientMyThing, implement the necessary methods. Okay so far, but those two classes need to know about each other in order to return instances of each other.

I think I can do it by forward-declaring Clojure functions make-transient and make-persistent, then defining the deftype (by referring to that function), then implementing the functions with the now-existing types, but it seems pretty gross to me. Is there a better option?

Edit: that works, but it's still gross.

Plumbic answered 19/6, 2011 at 1:51 Comment(3)
not able to test it right now but it but it might be possible to add the functionality after you have defined the two types using "extend-type"?Fernandes
Currently, there's no other option than forward declaration of helper functions. I don't think it will incur a notable perf penalty (especially in 1.3). However there's another thing that may work: defining the transient type with reify inside the asTransient method -- I didn't test but there's good chances you'll hit another compiler limitation (if the stack trace talks about a stub, that's the one).Polynomial
cgrand's comment was perfect. I'd accept it if it were an answer; just adding a comment here so anyone who happens across the question knows how to solve it.Plumbic
S
5

In Clojure 1.3 and later, a slightly simpler solution is to rely on the constructor functions that Clojure creates for your deftypes, ->transient and ->persistent!. Since those are functions, and not macros, you can forward declare them. Then you can use them, rather than your own make-transient and make-persistent, and you don't have to implement them yourself.

Standoff answered 7/10, 2014 at 3:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.