Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala immutable linked list with cycles

In Scala, I need to make an immutable linked list with cycles. Something like:

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

But it doesn't work. How do I make an immutable linked list with cycles?

like image 689
Michael Lafayette Avatar asked Feb 07 '23 01:02

Michael Lafayette


1 Answers

Use lazy values and by-name parameters to defer initialization:

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)

Output:

1
2
3
1
2
3
1
2
3
1
like image 53
Aivean Avatar answered Feb 08 '23 14:02

Aivean