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' が Char ではなく最も一般的な Any を選択する理由を理解してください。言語仕様のどのトピックを読む必要がありますか? ありがとう。

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 に答える