Is it possible to create circular references in Clojure?

喜欢而已 提交于 2019-12-03 09:43:52

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.

In Clojure most circular data structures will explicitely go through a ref type of some kind (eg atom).

However you can create a circular sequence (it's somewhat an oxymoron):

(let [a (atom nil)] (reset! a (lazy-seq (cons 1 @a))))

And since Clojure 1.2 with deftype you can create other datatypes which can introduce circularity without using explicitely (from the usercode at least) any kind of ref type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!