在斯卡拉,我需要做一个不变的链接列表与周期。例如:斯卡拉与周期不可变链接列表
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
但它不起作用。我如何使用循环创建不可变链接列表?
在斯卡拉,我需要做一个不变的链接列表与周期。例如:斯卡拉与周期不可变链接列表
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
但它不起作用。我如何使用循环创建不可变链接列表?
懒的建筑:
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)
不可改变的链接与周期表,如果他们懒惰是可能的。 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
使用延迟值和名称参数推迟初始化:
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
3
1
2
3
1
2
3
1