Reputation: 35
I have a problem: I have a list in scala like this (List("Entry1", "Entry2", "Entry3")) and I want to print this list functional. So I don't want to use any kind of loops.
I know it is possible using some kind of this code:
def test(input:List[_])
input match
{
case //and what now?
case _ => //recursion I guess?
}
I want to print this list using this method, every element on a new line.
Could someone help me please?
Thanks!
Upvotes: 0
Views: 6158
Reputation: 52681
The standard way would be:
val xs = List("Entry1", "Entry2", "Entry3")
xs.foreach(println)
Or, if you want the index with it:
xs.zipWithIndex.foreach { case (x,i) => println(i + ": " + x) }
But I take it from your question that this is an exercise in writing a recursive function, so knowing the built-in way doesn't really help you.
So, if you want to do it yourself, recursively, without the built-in foreach
method, try this:
@tailrec
def printList[T](list: List[T]) {
list match {
case head :: tail =>
println(head)
printList(tail)
case Nil =>
}
}
printList(List("Entry1", "Entry2", "Entry3"))
UPDATE: Regarding your comment about having the list index, try this:
def printList[T](list: List[T]) {
@tailrec
def inner(list: List[T], i: Int) {
list match {
case head :: tail =>
println(i + ": " + head)
inner(tail, i + 1)
case Nil =>
}
}
inner(list, 0)
}
Upvotes: 8
Reputation: 1749
Another solution using the list API :
List("Entry1", "Entry2", "Entry3").zipWithIndex.foreach(t => println(t._2 + ":" + t._1))
Upvotes: 1