简体   繁体   中英

Polymorphic type error during recursion - how to solve?

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));

If you replace StreamTrait.empty with Empty is compiles OK.

No idea if it works...

Seems that i had another function defined that called this unfold method with wrong parameters... silly me, thanks anyways:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM