... 或者 Haskell 程序员不得不编写 Scala 代码的事故,第 5 部分。
我在 Scala 中有以下结构:
case class ResourceTree(
resources: Map[String, ResourceTree]
)
而且,使用 Cats,我想定义Semigroup
它的一个实例。
object ResourceTreeInstances {
implicit val semigroupInstance = new Semigroup[ResourceTree] {
override def combine(x: ResourceTree, y: ResourceTree): ResourceTree = {
ResourceTree(
x.resources |+| y.resources
)
}
}
这将导致以下错误:
value |+| is not a member of Map[String, ResourceTree]
[error] Note: implicit value semigroupInstance is not applicable here because it comes after the application point and it lacks an explicit result type
[error] x.resources |+| y.resource
所以,我的猜测是,由于我正在为Semigroup
Scala 编译器定义实例,因此无法派生Semigroup
of的实例Map[String, ResourceTree]
。这似乎得到了证实,因为编译了以下实例:
implicit val semigroupInstance = new Semigroup[ResourceTree] {
override def combine(x: ResourceTree, y: ResourceTree): ResourceTree = {
dummyCombine(x, y)
}
}
// FIXME: see if there's a better way to avoid the "no instance of Semigroup" problem
def dummyCombine(x: ResourceTree, y: ResourceTree): ResourceTree = {
ResourceTree(
x.resources |+| y.resources
)
}
我真的希望我错了,因为如果这是在 Scala 中为 Semigroup 定义实例的正确方法,我将开始考虑放弃用这种语言做 FP 的想法。
有没有更好的办法?