2016-09-27 17 views
2

スカラでは、サイクルで不変リンクリストを作成する必要があります。何かのように:スカラ不変リンクリストとサイクル

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 

しかし、それは動作しません。どのように私はサイクルで不変のリンクリストを作るのですか?

答えて

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

不変リンクリストが可能です。 Scalaは既にレイジーリストをサポートしています。これは、印刷されます

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 
4

使用怠惰な値と初期化を延期することで、名前のパラメータ:

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 
を彼らは Stream Sと呼ばれています
関連する問題