[英]Scala: Implementing a generic fold
I don't understand why thid fold doesn't compile. 我不明白为什么锡德褶皱无法编译。 Could anyone give me a clue?
谁能给我一个线索?
sealed trait ListG[A] {
def fold[A,B](end: B, f: (A,B) => B): B = this match {
case End() => end
case Cons(hd,tl) => f(hd, tl.fold(end,f))
}
}
Error:(20, 28) type mismatch; 错误:(20,28)类型不匹配; found : hd.type (with underlying type A) required: A case Cons(hd,tl) => f(hd, tl.fold(end,f)) ^ final case class EndA extends ListG[A] final case class Cons[A](hd:A, tl:ListG[A]) extends ListG[A]
找到:hd.type(具有基础类型A)必需:案例Cons(hd,tl)=> f(hd,tl.fold(end,f))^最终案例类EndA扩展了ListG [A]最终案例类Cons [A](hd:A,tl:ListG [A])扩展了ListG [A]
你的阴影类型参数A
的ListG
当你定义一个额外的类型参数A
对fold
功能。
Adding type ascription appears to fix the problem. 添加类型说明似乎可以解决该问题。
case Cons(hd:A, tl) => ...
^^
There is a warning about type erasure but it does compile and appears to run. 出现有关类型擦除的警告,但它会编译并似乎正在运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.