Semigroup 的目标是确保关联性和闭合性 monoid 的目标是基于 Semigroup 并提供额外的 Identity。当我使用 |+| semigroup appender,为什么我定义隐式幺半群而不是隐式半群
这是我正在使用 reduceLeft 的代码,它不需要初始值
val result1 = List(Staff("John", 36), Staff("Andrew", 30))
val result2 = List(Staff("John", 40), Staff("Danny", 30))
val result3 = List(Staff("Andrew", 30))
val result4: List[Staff] = List()
implicit val staffListSemigroup = new Monoid[List[Staff]] {
override def zero: List[Staff] = Nil
override def append(f1: List[Staff], f2: => List[Staff]): List[Staff] = {
val mapSemigroup = f1.map(t => (t.name, t.numberOfTasks)).toMap |+| f2.map(t => (t.name, t.numberOfTasks)).toMap
mapSemigroup.map(t => Staff(t._1, t._2)).toList
}
}
val result = List(result1, result2, result3, result4).reduceLeft(_ |+| _)
assert(result.size == 3)
如果 staffListSemigroup 为 Semigroup[List[Staff]],则编译错误为 value |+| 不是 List[SemigroupSpec.this.Staff] 的成员
另外,|+| 的定义 在半群内
final class SemigroupOps[F] private[syntax](val self: F)(implicit val F: Semigroup[F]) extends Ops[F] {
////
final def |+|(other: => F): F = F.append(self, other)
final def mappend(other: => F): F = F.append(self, other)
final def ⊹(other: => F): F = F.append(self, other)
////
}
提前谢谢了
编辑
其次是@Travis 的回答,我认为这是不正确的。对于隐式值,特定值将始终覆盖通用值。这是我刚刚写的一个代码示例:
case class Foo(i : Int, s : String)
class Test[T] {
def print = "print test"
}
implicit val test = new Test[Any]
implicit val testMoreSpecific = new Test[Foo] {
override def print = "print Foo"
}
def doStuff[A](implicit test: Test[A]) = {
test.print
}
doStuff[Foo] //it successfully print out print Foo
doStuff //compilation error, ambiguous implicit value found
那是因为在 Scalaz 中,没有指定像 Foo 这样的方法中指定的类型。