我正在尝试在Scala(通用流)中定义一个HKT,我不确定为什么在尝试实现exist方法时会出现类型不匹配错误:
到目前为止,这是我的代码
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)
^
谢谢!
答案 0 :(得分:3)
您要将exists()
放在SmartStream
对象(即单例)中。这意味着this
的类型为SmartStream.type
,不能再为其他任何内容。
如果将exists()
移至特征,并删除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)
}
}
}
设计中可能还存在其他缺陷,但至少可以编译。