简体   繁体   中英

Scala - What type should I use for trees of a set depth?

Suppose I want to create trees of a certain set depth, that is, the path length from the top of the tree to any leaf node is some fixed number. Ideally, the type checker would be able to verify that you are creating and using these trees correctly. For my problem, I implemented something like:

import collection.mutable.HashMap

abstract class TreeNode[A, B] {
  def insert(data: B, path: List[A])
}

class TwigNode[A, B] extends TreeNode[A, B] {
  val hm = new HashMap[A, B]

  def insert(data: B, path: List[A]) {
    hm(path.head) = data
  }
}

class BranchNode[A, B](depth: Int) extends TreeNode[A, B] {
  val hm = new HashMap[A, TreeNode[A, B]].withDefaultValue(
    if (depth == 2)
      new TwigNode[A, B]
    else
      new BranchNode[A, B](depth - 1)
    )

  def insert(data: B, path: List[A]) {
    hm(path.head).insert(data, path.tail)
  }
}

But the type checker isn't helping me here. If there is a bug in the insert method (or any other method) the tree could end up with leaf nodes at different distances. Is it possible to get the type checker to verify everything is correct, with resorting to something crazy (implementing Peano arithmetic in the type system?) or having ugly types like BranchNode[BranchNode[BranchNode[BranchNode[TwigNode[A]]]]] ?

The feature you want is often referred to as a dependent type system. And at the moment there is no common used programming language with that feature implemented. Though you can generate more or less practical dependent type systems in C++, they will look somewhat similar to BranchNode[BranchNode[BranchNode[BranchNode[TwigNode[A]]]]]

So nothing but those ugly things that you have already considered are practical in Scala.

Although there are some mathematical methods to build and handle complete trees. But they are to be omitted because your disinterest on those is predictable.

This kind of thing requires dependent types and is not supported by Scala.

Yet, you can do it by using church numeral representation in the type system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM