Im new to scala and im following the book "FP in Scala". Right now i am writing an unfold function for the Stream datatype, which i am recreating. The problem is, that the type checker tells me that the polymorphic type seems to be wrong for the recursion.
This is the Stream trait and its static object, including the unfold function:
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))
}
}
}
The output is:
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));
Seems that i had another function defined that called this unfold method with wrong parameters... silly me, thanks anyways :)