Reputation: 195
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; 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]
Upvotes: 0
Views: 262
Reputation: 51271
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.
Upvotes: 0
Reputation: 7247
You're shadowing type parameter A
of ListG
when you define an additional type parameter A
on the fold
function.
Upvotes: 5