5

下一个代码

  def f(chars: List[Char]): List[List[Char]] = chars match {
    case Nil => List(Nil)
    case x :: xs => for {
      v <- f(xs)
    } yield List(x) :: v
  }

给出错误信息

- type mismatch;  found   : List[List[Any]]  required: List[List[Char]]

请帮助我理解为什么'for'在这里选择最通用的 Any 而不是 Char ?我应该阅读语言规范中的哪些主题?谢谢。

4

2 回答 2

10

结果,你是和yielding的混合体。Scala 将其向上转换为. 对于您的情况,以下任何一项都可以完成这项工作:List[List[List[Char]]]List[List[Char]]List[List[Any]]

scala>  def f(chars: List[Char]): List[List[Char]] = chars match {
     |     case Nil => List(Nil)
     |     case x :: xs => for {
     |       v <- f(xs)
     |     } yield x :: v
     |   }
f: (chars: List[Char])List[List[Char]]

scala>  def f(chars: List[Char]): List[List[Char]] = chars match {
     |     case Nil => List(Nil)
     |     case x :: xs => for {
     |       v <- f(xs)
     |     } yield List(x) ++ v
     |   }
f: (chars: List[Char])List[List[Char]]
于 2013-05-10T14:54:39.590 回答
6

问题是List(x)- 它需要x

首先,v遍历 的结果f(xs)f返回List[List[Char]]。这意味着结果将是List[X]X返回的类型在哪里yield

的类型vList[Char],因为它正在遍历 的内容f(xs)。所以我们必须弄清楚 的类型,它是在 aList(x) :: v前面加上a 。它不是将它们连接起来:它是将一个列表添加到仅包含字符的列表中。结果列表将同时包含和。List[Char]List[Char]CharList[Char]

由于唯一同时满足两者的类型是Any, then Xwill beAny和 for-comprehension 的结果List[Any]

于 2013-05-10T14:57:37.543 回答