Singly-linked list/Traversal: Difference between revisions

m (+Stata)
Line 1,235:
 
=={{header|Scala}}==
You can use pattern matching for traversing a list.
Scala has a '''Seq''' (for ''sequence'') trait
that is more general than singly-linked lists.
These two examples are equivalent for SLL,
but the second would be faster for other sequence types.
<lang scala>def traverse1[T](xs: Seq[T]): Unit = xs match {
case s if s.isEmpty => ()
case _ => { Console.println(xs.head);
traverse1(xs.tail)
}
}</lang>
 
<lang scala>
<lang scala>def traverse2[T](xs: Seq[T]) = for (x <- xs) Console.println(x)</lang>
/*
Here is a basic list definition
 
sealed trait List[+A]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
*/
 
<lang scala>def traverse1traverse[TA](xsas: SeqList[TA]): Unit = xsas match {
case Nil => print("End")
case Cons(h, t) => {
print(h + " ")
traverse(t)
}
}
}</lang>
 
=={{header|Scheme}}==
Anonymous user