【问题标题】:No such element Exception for ScalaScala 没有这样的元素例外
【发布时间】:2021-08-22 02:48:03
【问题描述】:

我正在为一门在线课程做作业。它是 Scala 中的函数式编程。我正在研究一个函数,该函数返回一个对列表,其中包含第一个索引中的字符和第二个索引中的出现次数。不幸的是,我遇到了一个错误。由于某种原因,我的模式匹配案例没有捕获 Nil 列表的案例。我收到没有这样的元素错误。谢谢!

这是我的代码

  def times(chars: List[Char]): List[(Char, Int)] = {
    // Need to recurse through list
    // Needs to be tail recursive
    def timesAcc(charList: List[Char], acc: List[(Char, Int)]): List[(Char, Int)] = {
      charList match {
        case Nil => acc
        case _ =>
      }

      if(!acc.exists(elem => elem._1 == charList.head)) {
        val count = charList.count(c => c == charList.head)
        timesAcc(charList.tail,(charList.head, count) :: acc)
      }else{
        timesAcc(charList.tail, acc)
      }

    }
    timesAcc(chars, List())
  }

【问题讨论】:

  • 您的括号不匹配(您过早关闭模式匹配)。模式匹配是无用的。您需要将所有逻辑移动到第二个case

标签: scala functional-programming


【解决方案1】:

在 Scala 中,一切都是表达。在您的情况下,它将从 charList 匹配返回值并执行 charList 下面的代码。在 scala 中,我们使用带有 @tailrec 注释的递归函数来避免堆栈溢出问题。

您的代码:

val a = charList match {
  case Nil => acc
  case _ =>
}

解决方案:

def times(chars: List[Char]): List[(Char, Int)] = {
  // Need to recurse through list
  // Needs to be tail recursive

  @tailrec
  def timesAcc(charList: List[Char], acc: Map[Char, Int]): Map[Char, Int] = {
    charList match {
      case head :: tail => acc.get(head) match {
        case Some(count) => timesAcc(tail, acc ++ Map(head -> (count + 1)))
        case _ => timesAcc(tail, acc ++ Map(head -> 1))
      }

      case _ => acc
    }
  }
  timesAcc(chars, Map.empty).toList
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2012-05-21
    • 2021-07-29
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多