2013-10-20 56 views
1

通過FP in Scala的Monoid章節的第一個練習,嘗試使用「listMonoid」創建特徵的新實現時發生編譯時錯誤。未找到泛型「A」

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 

如何創建listMonoid以便使用未指定的泛型類型?

回答

2

列表實際上稱爲自由monoid。你需要明確在列表Monoid的範圍創建A

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] 
    } 
} 
+0

嗨Alexlv - 我試過了,但我stlil越來越'錯誤:未發現:類型A'。 –

+3

@Kevin這應該工作,你有沒有改變val listMonoid來定義?我已經添加了完整的示例,只需複製/粘貼即可 – 4lex1v