我正在 Scala 中做一些 Scala 函数式编程 [MEAP] 一书中的练习。在“严格与懒惰”一章中,我必须为 Stream 实现一个 zipAll 实现。相关代码:
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]
def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
lazy val head = hd
lazy val tail = tl
Cons(() => head, () => tail)
}
def empty[A]: Stream[A] = Empty
def unfold[A, S](z: S)(f: S => Option[(A, S)]): Stream[A] = f(z) match {
case Some((a, s)) => cons(a, unfold(s)(f))
case None => empty
}
问题是我遇到了奇怪的类型不匹配。只要任一流有更多元素,zipAll 函数就应该继续遍历,并且它使用 Option 来指示每个流是否已耗尽。函数 zipAll 必须通过展开(上面)来实现。我有这本书的作者完成的正确答案,他们没有实现简单的 zipAll 而是使用 zipWithAll 来抽象它。然而,我的解决方案并不是抽象的,我想知道为什么它不起作用。
我的回答:
def myZipAll[B, C](s2: Stream[B]): Stream[(Option[A], Option[B])] =
unfold((this, s2)){
case (Empty, Empty) => None
case (Cons(h, t), Empty) => Some( ((Some(h()), Option.empty[B]), (t(), empty[B])) )
case (Empty, Cons(h, t)) => Some( ((Option.empty[A], Some(h())), (empty[A], t())) )
case (Cons(h1, t1), Cons(h2, t2)) => Some( ( (Some(h1()), Some(h2())), (t1(), t2())) )
}
作者的解决方案(有效):
def zipWithAll[B, C](s2: Stream[B])(f: (Option[A], Option[B]) => C): Stream[C] =
unfold((this, s2)){
case (Empty, Empty) => None
case (Cons(h, t), Empty) => Some( (f(Some(h()), Option.empty[B]), (t(), empty[B])) )
case (Empty, Cons(h, t)) => Some( (f(Option.empty[A], Some(h())), (empty[A], t())) )
case (Cons(h1, t1), Cons(h2, t2)) => Some( ( f(Some(h1()), Some(h2())), (t1(), t2())) )
}
def zipAll[B](s2: Stream[B]): Stream[(Option[A], Option[B])] =
zipWithAll(s2)((_, _))
来自 Intellij 的错误消息显示:“Stream[(Any, Any)] 类型的表达式”不符合预期类型 Stream[(Option[A], Option[B])]。
最佳答案
您的解决方案适用于我的命令行,因此它可能是一个 IntelliJ 错误。当您看到这种类型的错误时,编译器完成的类型推断由于某种原因而失败,因此您会得到“Any”。我的解决方案与您的解决方案类似,但我在您使用 Option.empty[A] 和 Option.empty[B] 的地方使用 None 。尝试一下。
关于scala - Scala 中 zipAll 实现中奇怪的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585759/