Scala: circular references in immutable data types?

前端 未结 5 661
逝去的感伤
逝去的感伤 2020-12-03 06:47

I\'ve been thinking for a while how I would go about implementing a doubly-linked tree or list in Scala just using immutable case classes. For most \"update\" operations, I\

5条回答
  •  一向
    一向 (楼主)
    2020-12-03 07:22

    Immutability in scala means that after we are finished constructing an object it should not change. During the object construction it is is actually mutable. The solution is to pass a piece of code to the constructor of the object that calculates the required values before the fields become immutable.

    {
      // Create a with the creation of b as a parameter.
      val a=new A( (uncomplete:A)=>new B(uncomplete) )
    }
    
    class A( bFactory:A=>B){
      //Call the bFactory then assign the result to b.
      val b=bFactory(this);
    }
    
    class B(val a:A){
    }
    

    Since the question talks about trees I will also include the generation of a basic tree using the same technique.

     class MakeTree {
      val tree = new Node(None, createSubTree _, createSubTree _);
    
      def createSubTree(parent: Node): Option[Node] = {
        if (parent.depth < 3)
          Some(new Node(None, createSubNode _, createSubNode _))
        else
          None
      }
    }
    
    class Node(val parent: Option[Node], leftFactory: (Node) => Option[Node], rightFactory: (Node) => Option[Node]) {
      val left = leftFactory(this);
      val right = rightFactory(this);
    
      def depth(): Int = parent.map(_.depth + 1).getOrElse(0);
    }
    

    Doing the construction like this leaves a pure immutable structure without the added overhead of accessing lazy values.

提交回复
热议问题