【问题标题】:SCALA PAttern matching with recursive in LISTSCALA PAttern 与 LIST 中的递归匹配
【发布时间】:2018-12-15 09:54:10
【问题描述】:

递归函数每次调用后如何打印list的元素?

 def multiply(list: List[Int]): Unit =list match {
        case Nil => 1
        case n :: rest => n * multiply(rest)
    }

每次调用 multiply() 时,我都想查看它要处理的列表元素。

【问题讨论】:

  • 家庭作业? println(n)
  • 每次迭代后调用print
  • 我应该在哪里调用 print 因为我尝试了内部函数然后它给出了错误,你可以分享代码吗?

标签: scala


【解决方案1】:

您的方法应该返回Int 而不是Unit。要迭代打印元素,只需在case head :: tail 下方插入println

def multiply(list: List[Int]): Int = list match {
    case Nil => 1
    case n :: rest =>
      println(n)
      n * multiply(rest)
  }

multiply(List(1,2,3,4))
// 1
// 2
// 3
// 4
// res1: Int = 24

【讨论】:

  • 得到了 def multiply(list: List[Int]): Int = list match { case Nil => 1 case n :: rest => println(list) n * multiply(rest) }跨度>
猜你喜欢
  • 2015-09-12
  • 1970-01-01
  • 2014-09-22
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2013-06-08
相关资源
最近更新 更多