Note that there are some explanatory texts on larger screens.

plurals
  1. POClojure - reset! atom causing a stack overflow
    primarykey
    data
    text
    <p>I am learning clojure and just playing with atoms and refs. Here is a simple tree implementation, but it is causing a stack overflow when executing the add-child method:</p> <pre><code>(ns mytree) (defprotocol PNode (add-child [this parent] "add 'this' node to the parent")) (defrecord Node [id parent name children] PNode (add-child [this p] (println "adding this to children of parent") (dosync (alter (:children p) conj this)) ;following causes a stack overflow -why? ; (println "reseting parent of this") ; (reset! parent p) )) (defn create-node [id name] (Node. id (atom nil) name (ref ()))) </code></pre> <p>Here is a sample session from REPL:</p> <pre><code>&gt;mytree&gt; (def root (create-node 1 "CEO")) &gt;#'mytree/root &gt;mytree&gt; (def child (create-node 2 "VP1")) &gt;#'mytree/child &gt;mytree&gt; (add-child child root) &gt;adding this to children of parent &gt;(#:mytree.Node{:id 2, :parent #&lt;Atom@4dffa9d: nil&gt;, :name "VP1", :children #&lt;Ref@cbe5beb: ()&gt;}) &gt;mytree&gt; root &gt;#:mytree.Node{:id 1, :parent #&lt;Atom@44896098: nil&gt;, :name "CEO", :children #&lt;Ref@2a75733a: &gt;(#:mytree.Node{:id 2, :parent #&lt;Atom@4dffa9d: nil&gt;, :name "VP1", :children #&lt;Ref@cbe5beb: ()&gt;})&gt;} &gt;mytree&gt; (def child2 (create-node 3 "VP2")) &gt;#'mytree/child2 resetting parent to child2 works &gt;mytree&gt; (reset! (:parent child) child2) &gt;#:mytree.Node{:id 3, :parent #&lt;Atom@43c32b82: nil&gt;, :name "VP2", :children #&lt;Ref@425d868f: ()&gt;} but resetting parent to root causes stack overflow - why?? &gt;mytree&gt; (reset! (:parent child) root) &gt;; Evaluation aborted. </code></pre> <p>As you can see above, reseting parent of child to child2 works, but resetting it to root causes a stack overflow. Can you help me understand why?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload