rodbs
rodbs

Reputation: 195

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

Answers (2)

jwvh
jwvh

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

Ryan
Ryan

Reputation: 7247

You're shadowing type parameter A of ListG when you define an additional type parameter A on the fold function.

Upvotes: 5

Related Questions