Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create circular references in Clojure?

Tags:

Ignoring native interop and transients, is it possible to create any data structures in Clojure that contain direct circular references ?

It would seem that immutable data structures can only ever contain references to previous versions of themselves. Are there any Clojure APIs that could create a new data structure that has a reference to itself ?

Scheme has the letrec form which allows mutually recursive structures to be created - but, as far as I can tell, Clojure does not have anything similar.

This question is related to porting Clojure to iOS - which does not have garbage collection, but does have reference counting.

like image 691
Nick Main Avatar asked Sep 12 '10 19:09

Nick Main


1 Answers

You can create a circular reference very easily by putting some form of reference inside a data structure, then updating the reference to point back to the overall structure.

A trivial example:

(def a [(atom nil)])  (reset! (first a) a) 

This will create a list with one element, which is an atom that points back at the list.

like image 112
mikera Avatar answered Oct 19 '22 07:10

mikera