0

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!

3 Answers 3

8

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)
}
Sign up to request clarification or add additional context in comments.

7 Comments

The way you defined that, it will fail when the list is Nil
Is it possible to add a Nil function?
What does printList[T] (I'm talking about the T) mean?
The T is a generic type parameter. It just means that the function accepts a List of anything, and calls that anything T. Search for "scala generics" if you want to read more about it.
Oke, and is it also possible to get the list item number (like list(0) but then in the functional loop)?
|
1

Another solution using the list API :

List("Entry1", "Entry2", "Entry3").zipWithIndex.foreach(t => println(t._2 + ":" + t._1))

1 Comment

@user1545846 foreach isn't a loop. It's a higher order function. It is definitely 1000000% better than using recursion here. You shouldn't expect the I/O operation to be "functional" anyway - it is side-effecting by nature.
0

List("LALA", "PEPE", "JOJO").map(println)

1 Comment

You should use foreach, not map, because map will unnecessarily construct a new List that contains not but Unit instances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.