我正在尝试在Scala中定义一个HKT(一个通用流),我不确定为什么我在尝试实现exists方法时遇到类型不匹配错误:
到目前为止,这是我的代码
sealed trait SmartStream[+A]
case object Nil extends SmartStream[Nothing]
case class Cons[+A](h : () => A, t : () => SmartStream[A]) extends SmartStream[A]
object SmartStream {
def nil[A] : SmartStream[A] = Nil
def cons[A](h : => A, t : => SmartStream[A]) : SmartStream[A] = {
lazy val g = h
lazy val u = t
Cons(() => g, () => u)
}
def apply[A](as: A*) : SmartStream[A] = {
if (as.isEmpty) nil
else cons( as.head, apply(as.tail: _*))
}
def exists[A](p : A => Boolean) : Boolean = {
this match {
case Nil => false
case Cons(h, t) => p(h()) || t().exists(p)
}
}
}
我得到的错误是:
ScalaFiddle.scala:21: error: pattern type is incompatible with expected type;
found : ScalaFiddle.this.Nil.type
required: ScalaFiddle.this.SmartStream.type
case Nil => false
^
ScalaFiddle.scala:22: error: constructor cannot be instantiated to expected type;
found : ScalaFiddle.this.Cons[A]
required: ScalaFiddle.this.SmartStream.type
case Cons(h, t) => p(h()) || t().exists(p)
^
提前致谢!
你将exists()
放在SmartStream
对象(即单身人士)中。这意味着this
是SmartStream.type
类型,永远不会是其他任何东西。
如果将exists()
移动到trait,并删除type参数,则会编译。
sealed trait SmartStream[+A] {
def exists(p : A => Boolean) : Boolean = {
this match {
case Nil => false
case Cons(h, t) => p(h()) || t().exists(p)
}
}
}
设计中可能存在其他缺陷,但至少可以编译。