3

我正在制作一个用于组合重试执行策略的 Monoid,而 RetryExecutor[T] 是基于类型的。我已经定义了以下基本类型和一个幺半群:

trait RetryExecutor[C] {
  def retry[T](f: C => T)(context: C): T

  def predicate: Option[Throwable]
  def application: Unit
  val retryEligible: PartialFunction[Throwable, Boolean]
}

object RetryExecutor {
  implicit def retryExecutorMonoid[A] = new Monoid[RetryExecutor[A]] {
  ...
}

和一些基本类型,如:

case class LinearDelayingRetryExecutor[C](delayInMillis: Long)(val retryEligible: PartialFunction[Throwable, Boolean]) extends RetryExecutor[C] {
  override def predicate: Option[Throwable] = None
  override def application = Thread.sleep(delayInMillis)
}

case class RetryWithCountExecutor[C](maximumRetries: Int)(val retryEligible: PartialFunction[Throwable, Boolean])(implicit val logger: Logger) extends RetryExecutor[C] {
  var remainingTries = maximumRetries + 1

  override def application: Unit = {
    remainingTries = remainingTries - 1
  }

  override def predicate: Option[Throwable] = {
    if (remainingTries > 0) None
      else Some(RetryingException("Retry count of " + maximumRetries + " exceeded for operation"))
  }
}

我可以手动组合它们:

val valid: PartialFunction[Throwable, Boolean] = { case x: TestException => true }

val monoid = RetryExecutor.retryExecutorMonoid[Int]
val x = monoid.append(RetryWithCountExecutor[Int](3)(valid), LinearDelayingRetryExecutor(100)(valid))

但是当我尝试使用附加运算符时:

val x = RetryWithCountExecutor[Int](3)(valid) |+| LinearDelayingRetryExecutor(100)(valid)

我得到一个编译错误:

[error] /Users/1000306652a/work/src/test/scala/com/foo/bar/RetryExecutorSpec.scala:25: value |+| is not a member of com.foo.bar.retry.RetryWithCountExecutor[Int]
[error]   val k: RetryExecutor[Int] = RetryWithCountExecutor[Int](3)(valid) |+| BackingOffRetryExecutor[Int](100)(valid)
4

1 回答 1

5

这是一个更简单的情况下的相同问题:

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> Option(1) |+| Option(2)
res0: Option[Int] = Some(3)

scala> Monoid[Option[Int]].append(Some(1), Some(2))
res1: Option[Int] = Some(3)

scala> Some(1) |+| Some(2)
<console>:14: error: value |+| is not a member of Some[Int]
              Some(1) |+| Some(2)
                      ^

问题(这不是真正的问题,更多的是设计决策)Monoid不是协变的——拥有 aMonoid[Option[Int]]并不意味着我拥有Monoid[Some[Int]].

理想的解决方案是为返回值类型作为超类型的子类型提供构造函数。继续我们的Option示例,Scalaz 将这些构造函数提供为somenone

scala> some(1) |+| some(2)
res3: Option[Int] = Some(3)

scala> some(1) |+| none
res4: Option[Int] = Some(1)

当然,您也可以显式地向上转换值,但是如果您可以避免使用子类型,那么您的生活将会简单得多。

于 2014-10-03T19:05:24.497 回答