【问题标题】:Getting a type error in a recursive flatten method implementation在递归展平方法实现中出现类型错误
【发布时间】:2016-05-13 12:47:34
【问题描述】:

我正在尝试学习 scala。今天我正在尝试编写一个简单的递归方法来展平嵌套列表。我知道有一个可以调用的 flatten 函数,但我正在尝试从头开始。

我收到类型不匹配错误,我正在尝试了解原因。 'A' 是什么类型的变量。

def flatten[A](lst:List[List[A]):List[A] = lst match{

case Nil=> Nil
case (h:List[A])::tail=> flatten(h)::flatten(tail)
case h :: tail=> flatten(tail)
}

【问题讨论】:

标签: scala recursion pattern-matching


【解决方案1】:

flatten(h) 是一个编译器错误,因为h 是一个List[A],但flatten 需要一个嵌套的List[List[A]]。尝试简单地将h 与扁平化tail 的结果连接起来:

def flatten[A](lst: List[List[A]]): List[A] = lst match {
  case Nil => Nil
  case h :: tail => h ::: flatten(tail)
}

例子:

scala> flatten(List(List("a", "b"), List("c", "d")))
res0: List[String] = List(a, b, c, d)

scala> flatten(List(List(1, 2), List(3, 4)))
res1: List[Int] = List(1, 2, 3, 4)

【讨论】:

  • 太棒了!我很抱歉,因为我是 scala 的新手,但是 ':::' 的功能是什么?
  • 它合并了两个列表。 List(1, 2) ::: List(3, 4) = List(1, 2, 3, 4).
  • 好的。谢谢!本书中的这个特殊练习仅使用模式匹配 '::'。如果我要使用它,我会只调用和模式匹配两个正面和反面吗?
猜你喜欢
  • 2017-04-23
  • 2017-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
相关资源
最近更新 更多