通过FP in Scala的Monoid章节的第一次练习,尝试使用“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
如何创建listMonoid以使用未指定的泛型类型?
答案 0 :(得分:2)
列表实际上是一个免费的幺半群。您需要在列表A
范围内明确创建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]
}
}