Scala不可变链表与循环

时间:2016-09-27 03:31:39

标签: scala linked-list

在Scala中,我需要使用循环创建一个不可变的链表。类似的东西:

case class Node(element: Int, next: Node)
val linkedList = Node(1, Node(2, null))
val cycle = Node(3, cycle)

cycle.next // this should go back to the same element

但它不起作用。如何使用循环创建不可变的链表?

3 个答案:

答案 0 :(得分:5)

使用延迟值和按名称参数来推迟初始化:

/**
 *
 * @var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\LISARDO\Foerderland\Domain\Model\MyFileReference>
 * @lazy
 */
protected $media;

输出:

class Node(val element: Int, next_ : => Node) {
  lazy val next = next_
}

lazy val root: Node =
  new Node(1,
    new Node(2,
      new Node(3, root)
    )
  )

// tail-recursive print function as a bonus
def printRec(node: Node, depth: Int): Unit = if (depth > 0) {
  println(node.element)
  printRec(node.next, depth - 1)
}

printRec(root, 10)

答案 1 :(得分:2)

懒惰的建筑:

scala> case class Node(element: Int)(next0: => Node) { def next = next0 }
defined class Node

scala> object X { val cycle: Node = Node(3)(cycle) }
defined object X

scala> X.cycle
res0: Node = Node(3)

scala> X.cycle.next
res1: Node = Node(3)

答案 2 :(得分:1)

如果它们是惰性的,则可以使用具有周期的不可变链接列表。 Scala已经支持懒惰列表。它们被称为Stream s:

val stream: Stream[Int] = 1 #:: 2 #:: 3 #:: stream
for { i <- stream.take(10) } {
  println(i)
}

这将打印:

1
2
3
1
2
3
1
2
3
1