我正在研究Scala并尝试实现自定义类型的一些抽象。为具体类定义scalaz monoids非常简单。但是如何为类型层次结构声明一个Monoid?假设这段代码:
{{1}}
如何使状态A()| + | B()在上面的例子中是可行的吗?
答案 0 :(得分:1)
编译:
<string name="welcome_boy">Welcome boy</string>
<string name="welcome_girl">Welcome girl</string>
if (isBoy())
txtWelcome.setText(getResources().getString(R.id.welcome_boy));
else
txtWelcome.setText(getResources().getString(R.id.welcome_girl));
如果你告诉Scala的可怕类型推断器是什么意思,你的例子就会编译:
import scalaz._, Scalaz._
sealed trait Base
case class A(a: Int) extends Base
case class B(b: Int) extends Base
object N extends Base
object BullShit {
// Wanna one monoid for all the Base's
implicit val sg: Semigroup[Base] = new Semigroup[Base] {
override def append(f1: Base, f2: => Base): Base = f1 match {
case A(a) => f2 match {
case A(a1) => A(a + a1)
case B(b) => A(a + b)
case N => N
}
case B(b) => f2 match {
case A(a) => B(a + b)
case B(b1) => B(b + b1)
case N => N
}
case N => f2
}
}
println((A(1): Base) |+| (B(2): Base))
}