Kevin Meredith
Kevin Meredith

Reputation: 41909

Generic Type "A" Not Found

Going through the first exercise of FP in Scala's Monoid chapter, a compile-time error occurred when trying to create a new implementation of a trait in with "listMonoid."

object MonoidTesting1 {
    trait Monoid[A] {
        def op(a1: A, a2: A): A
        def zero: A
    }

    val listMonoid = new Monoid[List[A]] {
        def op(a1: List[A], a2: List[A]) = a1 ++ a2
        val zero = Nil
    }
}


C:\Users\Kevin\Workspace\side-work\Monoid>scalac MonoidTesting.scala
MonoidTesting.scala:12: error: not found: type A
        val listMonoid = new Monoid[List[A]] {
                                         ^
MonoidTesting.scala:13: error: not found: type A
                def op(a1: List[A], a2: List[A]) = a1 ++ a2
                                ^
MonoidTesting.scala:13: error: not found: type A
                def op(a1: List[A], a2: List[A]) = a1 ++ a2
                                             ^
three errors found

How can I create listMonoid in order to use an unspecified, generic type?

Upvotes: 1

Views: 1099

Answers (1)

4lex1v
4lex1v

Reputation: 21557

List is what actually called a free monoid. You need explicitly create A in scope of list Monoid:

object MonoidTest {
  trait Monoid[A] {
    def op(a1: A, a2: A): A
    def zero: A
  }

  def listMonoid[A] = new Monoid[List[A]] {
    def op(a1: List[A], a2: List[A]) = a1 ++ a2
    val zero = List.empty[A]
  }
}

Upvotes: 2

Related Questions