简体   繁体   English

递归期间的多态类型错误 - 如何解决?

[英]Polymorphic type error during recursion - how to solve?

Im new to scala and im following the book "FP in Scala".我是 scala 的新手,我正在关注“Scala 中的 FP”一书。 Right now i am writing an unfold function for the Stream datatype, which i am recreating.现在我正在为 Stream 数据类型编写展开 function,我正在重新创建它。 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:这是 Stream 特征及其 static object,包括展开 ZC1C425268E68385D14ZA4:

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: output 是:

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));找到:[A(在方法展开中)](f:((A(在方法常量展开中),A(在方法常量展开中)))=>选项[(A(在方法展开中),(A(在方法常量展开中), A(在方法常量Unfold)))])StreamTrait[A(在方法展开)] 需要: StreamTrait[A(在方法常量Unfold)] def constantUnfold[A](a: A): StreamTrait[A] = unlock(a,身份(a));

If you replace StreamTrait.empty with Empty is compiles OK.如果将StreamTrait.empty替换为Empty则编译正常。

No idea if it works...不知道它是否有效......

Seems that i had another function defined that called this unfold method with wrong parameters... silly me, thanks anyways:)似乎我有另一个 function 定义了用错误的参数调用这个展开方法......我很傻,无论如何谢谢:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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