Scala: Это ошибка в черте LinkedListLike? - PullRequest
2 голосов
/ 16 декабря 2010

Это из источника стандартной библиотеки Scala из 2.8.1

  /** 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)?(т.е. поместить остальную часть этого связанного списка в конец списка, который мы вставляем?

Если нет, то почему? Код в настоящее время добавляет список, который мы вставляем, в конец текущего -то же, что и приложение.

1 Ответ

3 голосов
/ 16 декабря 2010

Я думаю, что это известная ошибка .

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).

...