3

A轮到的过程是怎样Nothing的?

def seq2map[A](src: Seq[A]): Map[A, A] = {
    def pair = for {
        f <- src.headOption
        s <- src.headOption
    } yield (f, s)
    Stream continually pair takeWhile(_ isDefined) toMap
}

错误:类型的表达Map[Nothing, Nothing]不符合预期的类型Map[A, A]

谢谢!

4

1 回答 1

4

我明白了

<console>:12: error: Cannot prove that Option[(A, A)] <:< (T, U).
           Stream continually pair takeWhile(_ isDefined) toMap
                                                          ^

因为

scala> val src = (1 to 10).toSeq
src: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala>     def pair = for {
     |         f <- src.headOption
     |         s <- src.headOption
     |     } yield (f, s)
pair: Option[(Int, Int)]

不是一对,而是一个选项。

scala> (Stream continually pair takeWhile (_.isDefined)).flatten
res0: scala.collection.immutable.Stream[(Int, Int)] = Stream((1,1), ?)

是对流。

只等比赛开始。

于 2014-10-12T00:05:02.037 回答