【问题标题】:Scala: Printing a Binary Tree That's a ClassScala:打印一个类的二叉树
【发布时间】:2020-02-18 19:34:49
【问题描述】:

您好,我是 Scala 新手,我很难让我的班级打印出一些值。

class TreeDemo[T](implicit o : T => Ordered[T]) {

      sealed trait BinaryTree
      case object Empty extends BinaryTree
      case class Node(left:BinaryTree, d:T, right:BinaryTree) extends BinaryTree


      // construct a "leaf" node
      def Leaf(d : T) : BinaryTree = Node(Empty,d,Empty)

      // remove all nodes equal to x from tree t
      def remove(t : BinaryTree, x : T) : BinaryTree = {
        replace(t, x, Empty)
      }

      val myTree = Node(Node(Leaf(1),2,Leaf(3)),4,Leaf(5))
      val x = remove(myTree, 2)

      def main (args: Array[String]) {
       println(x)
      }
}

从上面的代码中,我尝试打印删除 def,但出现错误。

【问题讨论】:

  • 请定义but I am getting errors
  • remove() 尚未在发布的代码中定义。而TreeDemo接收类型参数T,所以它是在类外定义的,所以不能在里面创建Leaf(1)(其中TInt)类定义。

标签: scala


【解决方案1】:
  • 如果您想从树中移除节点,那么您将需要var 值。我不确定,因为您的 sn-p 中缺少 replace
  • 正如cmets所指出的,Node只能取T,直到你实例化一个实际的TreeDemo,所以在定义类的时候,你不能创建特定类型的节点,例如Leaf(1)等. 因为这将是类型不匹配。
  • 似乎类型变量应该在 BinaryTree 本身,因为您希望您的演示尝试特定的树,并且它可以是协变的 (+T) 以允许 Empty 成为任何其他有效的 BinaryTree。
    • 节点的左右树应该与节点的类型相同。
  • 您可以覆盖 toString 以允许打印更多信息
  • 在类内部称为main 的方法不能用作入口点。在 Java 中,只有 static void main 将用作应用程序入口点。在 Scala 中,main 也应该是静态的(在对象而不是类中)才能运行。
sealed trait BinaryTree[+T]
case object Empty extends BinaryTree[Nothing]
class Node[T](var left:BinaryTree[T], var d:T, var right:BinaryTree[T])(implicit val ordering: Ordering[T]) extends BinaryTree[T] {
  override def toString: String = (left, right) match {
    case (Empty, Empty) => s"(${d})"
    case (Empty, right) => s"(${left},${d})"
    case (left, Empty) => s"(${d}, ${right})"
    case _ => s"(${left}, ${d}, ${right})"
  }
}
object Node{
  // define remove here (if static) or in the class
  def apply[T:Ordering](t: T) = new Node[T](Empty, t, Empty)
  def apply[T:Ordering](left:BinaryTree[T], t: T) = new Node[T](left, t, Empty)
  def apply[T:Ordering](left:BinaryTree[T], t: T, right:BinaryTree[T]) = new Node[T](left, t, right)
  def apply[T:Ordering](t: T, right:BinaryTree[T]) = new Node[T](Empty, t, right)
}
// either extend App, or have a main method, but use an object 
object TreeApp extends App {
  val myTree = Node(Node(Node(1),2,Node(3)),4,Node(5))
  println(myTree)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    相关资源
    最近更新 更多