【问题标题】:Scala: Is this a mistake in the LinkedListLike trait?Scala:这是 LinkedListLike 特征中的一个错误吗?
【发布时间】:2011-05-26 05:08:29
【问题描述】:

这是来自 2.8.1 的 Scala 标准库的源代码

  /** Append linked list `that` at current position of this linked list
   *  @return the list after append (this is the list itself if nonempty,
   *  or list `that` if list this is empty. )
   */
  def append(that: This): This = {
  @tailrec
    def loop(x: This) {
      if (x.next.isEmpty) x.next = that
      else loop(x.next)
    }
    if (isEmpty) that
    else { loop(repr); repr }
  }

  /** Insert linked list `that` at current position of this linked list
   *  @note this linked list must not be empty
   */
  def insert(that: This): Unit = {
    require(nonEmpty, "insert into empty list")
    if (that.nonEmpty) {
      next = next.append(that)
    }
  }

最后一行不应该是next = that.append(next)吗? (即将这个链表的其余部分放在我们要插入的列表的末尾?

如果不是,为什么不呢?该代码当前将我们插入的列表附加到当前列表的末尾 - 即与 apppend 相同。

【问题讨论】:

    标签: scala insert linked-list scala-2.8 scala-collections


    【解决方案1】:

    我认为是known bug。

    scala> import scala.collection.mutable._
    import scala.collection.mutable._
    
    scala> val foo = LinkedList(1, 2, 3, 4)
    foo: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3, 4)
    
    scala> foo.next insert LinkedList(5, 6, 7, 8)
    
    scala> foo
    res2: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3, 4, 5, 6, 7, 8)
    

    如果假设在“当前位置”插入LinkedList(5, 6, 7, 8),最终结果应该是LinkedList(1, 5, 6, 7, 8, 2, 3, 4)。

    【讨论】:

    • 是的,就是这个。似乎只有 2.8.1。也许我开始理解这个 Scala 的东西 :)
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2014-10-21
    • 2012-09-18
    • 2012-03-25
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多