Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>That's a very interesting question! As others have already noted, you have to change the entire path from root to the node you want to change. Immutable maps are very similar, and you may learn something <a href="http://blog.higher-order.net/2009/09/08/understanding-clojures-persistenthashmap-deftwice/" rel="nofollow">looking at Clojure's PersistentHashMap</a>.</p> <p>My recommendations are:</p> <ul> <li>Change <code>Tree</code> to <code>Node</code>. You even call it node in your question, so this is probably a better name.</li> <li>Pull <code>value</code> up to the base class. Once again, you talk about that in your question, so this is probably the right place for it.</li> <li>In your replace method, be sure that if neither a <code>Node</code> nor its children changes, don't create a new <code>Node</code>.</li> </ul> <p>Comments are in the code below:</p> <pre><code>// Changed Tree to Node, b/c that seems more accurate // Since Branch and Leaf both have value, pull that up to base class sealed abstract class Node(val value: Int) { /** Replaces this node or its children according to the given function */ def replace(fn: Node =&gt; Node): Node /** Helper to replace nodes that have a given value */ def replace(value: Int, node: Node): Node = replace(n =&gt; if (n.value == value) node else n) } // putting value first makes class structure match tree structure case class Branch(override val value: Int, left: Node, right: Node) extends Node(value) { def replace(fn: Node =&gt; Node): Node = { val newSelf = fn(this) if (this eq newSelf) { // this node's value didn't change, check the children val newLeft = left.replace(fn) val newRight = right.replace(fn) if ((left eq newLeft) &amp;&amp; (right eq newRight)) { // neither this node nor children changed this } else { // change the children of this node copy(left = newLeft, right = newRight) } } else { // change this node newSelf } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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