递归期间的多态类型错误 - 如何解决?
Polymorphic type error during recursion - how to solve?
我是 Scala 的新手,正在学习这本书 "FP in Scala"。
现在我正在为正在重新创建的 Stream 数据类型编写展开函数。
问题是,类型检查器告诉我递归的多态类型似乎是错误的。
这是 Stream trait 及其静态对象,包括展开函数:
sealed trait StreamTrait[+A] {}
case object Empty extends StreamTrait[Nothing];
case class Cons[+A](h: () => A, t: () => StreamTrait[A]) extends StreamTrait[A]
object StreamTrait {
def cons[A](hd: => A, tl: => StreamTrait[A]): StreamTrait[A] = {
lazy val head = hd;
lazy val tail = tl;
Cons(() => head, () => tail);
}
def unfold[A, S](z: S)(f: S => Option[(A, S)]): StreamTrait[A] = {
f(z) match {
case None => StreamTrait.empty
case Some(tuple) =>
StreamTrait.cons(tuple._1, unfold[A, S](tuple._2)(f))
}
}
}
输出为:
polymorphic expression cannot be instantiated to expected type;
found : [A(in method unfold)](f: ((A(in method constantUnfold), A(in method constantUnfold))) => Option[(A(in method unfold), (A(in method constantUnfold), A(in method constantUnfold)))])StreamTrait[A(in method unfold)]
required: StreamTrait[A(in method constantUnfold)]
def constantUnfold[A](a: A): StreamTrait[A] = unfold(a, identity(a));
如果将 StreamTrait.empty
替换为 Empty
则编译正常。
不知道它是否有效...
似乎我定义了另一个函数,该函数使用错误的参数调用此展开方法...愚蠢的我,无论如何谢谢:)
我是 Scala 的新手,正在学习这本书 "FP in Scala"。 现在我正在为正在重新创建的 Stream 数据类型编写展开函数。 问题是,类型检查器告诉我递归的多态类型似乎是错误的。
这是 Stream trait 及其静态对象,包括展开函数:
sealed trait StreamTrait[+A] {}
case object Empty extends StreamTrait[Nothing];
case class Cons[+A](h: () => A, t: () => StreamTrait[A]) extends StreamTrait[A]
object StreamTrait {
def cons[A](hd: => A, tl: => StreamTrait[A]): StreamTrait[A] = {
lazy val head = hd;
lazy val tail = tl;
Cons(() => head, () => tail);
}
def unfold[A, S](z: S)(f: S => Option[(A, S)]): StreamTrait[A] = {
f(z) match {
case None => StreamTrait.empty
case Some(tuple) =>
StreamTrait.cons(tuple._1, unfold[A, S](tuple._2)(f))
}
}
}
输出为:
polymorphic expression cannot be instantiated to expected type; found : [A(in method unfold)](f: ((A(in method constantUnfold), A(in method constantUnfold))) => Option[(A(in method unfold), (A(in method constantUnfold), A(in method constantUnfold)))])StreamTrait[A(in method unfold)] required: StreamTrait[A(in method constantUnfold)] def constantUnfold[A](a: A): StreamTrait[A] = unfold(a, identity(a));
如果将 StreamTrait.empty
替换为 Empty
则编译正常。
不知道它是否有效...
似乎我定义了另一个函数,该函数使用错误的参数调用此展开方法...愚蠢的我,无论如何谢谢:)