gpt4 book ai didi

Scala 错误 "pattern type is incompatible with expected type"

转载 作者:行者123 更新时间:2023-12-03 20:19:14 49 4
gpt4 key购买 nike

我正在研究“Scala 中的函数式编程”一书。第 5.2 章从以下代码开始:

sealed trait Stream[+A]
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

object Stream {
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 apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))

}

然后给出以下定义:
  def headOption: Option[A] = this match {
case Empty => None
case Cons(h, t) => Some(h())
}

我认为它应该是伴随对象的一部分。为了不立即出现编译错误,我添加了“headOption[A]”。但是,当我将结果包含到“对象流”中时,我收到错误“模式类型与预期类型不兼容;发现:需要 myPackage.Empty.type:myPackage.Stream.type”并带有下划线“Empty”。

我在这里有点失落。我究竟做错了什么?

最佳答案

它应该是 trait Stream[+A] 的一部分.

这里this指的是Stream (特征流不是伴随对象)。 Stream可以 Empty或者它可以是 Cons .所以模式匹配 this说得通。
headOption如果可用,给出流的第一个元素。

    case object Empty extends Stream[Nothing]

case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

sealed trait Stream[+A] {
def headOption: Option[A] = this match {
case Empty => None
case Cons(h, t) => Some(h())
}
}



object Stream {

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 apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))


}

Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)

case object Empty extends Stream[Nothing]

case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

sealed trait Stream[+A] {

def headOption: Option[A] = this match {
case Empty => None
case Cons(h, t) => Some(h())
}

}

object Stream {

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 apply[A](as: A*): Stream[A] =
if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))

}

// Exiting paste mode, now interpreting.

defined object Empty
defined class Cons
defined trait Stream
defined object Stream

scala> Stream.cons(1, Empty).headOption
res0: Option[Int] = Some(1)

关于Scala 错误 "pattern type is incompatible with expected type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092788/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com