2017-05-30 75 views
-1

我不明白为什么折叠不能编译。谁能给我一个线索?Scala:实现通用折叠

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

错误:(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 ] 最终案例类缺点[A](HD:A,TL:ListG [A])扩展ListG [A]

+2

将错误消息与代码一起发布 –

回答

0

添加类型归属似乎可以解决问题。

case Cons(hd:A, tl) => ... 
      ^^ 

存在关于类型擦除的警告,但它编译并且似乎运行。

4

你遮蔽ListGA类型参数,当你在fold定义一个额外的类型参数A功能。