Singly-linked list/Element definition: Difference between revisions

Line 1,200:
 
=={{header|Scala}}==
Immutable lists that you can use with pattern matching.
<lang scala>class Node(n: Int, link: Node) {
 
var data = n
<lang scala>
var next = link
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
 
object List {
def apply[A](as: A*): List[A] =
if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))
}
</lang>
 
Basic usage
The one below is more inline with the built-in definition
 
<lang scala>class Node {
def main(args: Array[String]): Unit = {
var data: Int
val words = List("Rosetta", "Code", "Scala", "Example")
var next = this
}
def this(n: Int, link: Node) {
this()
if (next != null){
data = n
next = link
}
}
</lang>
 
Anonymous user