List 使用scala打印列表函数

List 使用scala打印列表函数,list,scala,printing,recursion,functional-programming,List,Scala,Printing,Recursion,Functional Programming,我有一个问题:我在scala中有一个列表,比如ListEntry1,Entry2,Entry3 我想打印这个列表。所以我不想使用任何类型的循环 我知道使用某种代码是可能的: def test(input:List[_]) input match { case //and what now? case _ => //recursion I guess? } 我想用这个方法打印这个列表,每一个元素都在一个新行上 有人能帮我吗 谢谢 标准方法是: val xs = List("Entry1"

我有一个问题:我在scala中有一个列表,比如ListEntry1,Entry2,Entry3 我想打印这个列表。所以我不想使用任何类型的循环

我知道使用某种代码是可能的:

def test(input:List[_])
input match
{
case //and what now?
case _ => //recursion I guess?

}
我想用这个方法打印这个列表,每一个元素都在一个新行上

有人能帮我吗


谢谢

标准方法是:

val xs = List("Entry1", "Entry2", "Entry3")
xs.foreach(println)
或者,如果您需要索引,请执行以下操作:

xs.zipWithIndex.foreach { case (x,i) => println(i + ": " + x) }
但我从你的问题中了解到,这是一个编写递归函数的练习,因此了解内置方式并不能真正帮助你

因此,如果您希望自己递归地执行此操作,而不使用内置的foreach方法,请尝试以下方法:

@tailrec
def printList[T](list: List[T]) {
  list match {
    case head :: tail =>
      println(head)
      printList(tail)
    case Nil =>
  }
}

printList(List("Entry1", "Entry2", "Entry3"))
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)
}
更新:关于您对列表索引的评论,请尝试以下操作:

@tailrec
def printList[T](list: List[T]) {
  list match {
    case head :: tail =>
      println(head)
      printList(tail)
    case Nil =>
  }
}

printList(List("Entry1", "Entry2", "Entry3"))
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)
}

使用列表API的另一个解决方案:

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

ListLALA,PEPE,JOJO.mapprintln

按照您定义的方式,当列表为Nil时,它将失败。是否可以添加Nil函数?我说的printList[T]是什么意思?T是泛型类型参数。这只意味着函数接受任何内容的列表,并调用该列表。如果您想了解更多有关它的信息,请搜索scala泛型。Oke,是否也可以获取列表项编号,如list0,但随后在函数循环中?您应该使用foreach,而不是map,因为map将不必要地构造一个新列表,该列表只包含单元实例。@user1545846 foreach不是循环。这是一个高阶函数。这肯定比在这里使用递归要好1000000%。无论如何,您都不应该期望I/O操作是功能性的——它本质上是副作用的。