在scala中,在实现函数式repeatUntil时避免堆栈溢出

时间:2014-06-14 03:11:36

标签: scala

我正在尝试在scala中以函数方式实现repeatUntil,并且想知道是否有一种方法可以避免堆栈溢出,同时仍然具有良好的功能代码。这就是我所拥有的:

  def repeatUntil[T](f: => T, d: Duration, t: Int)(
    implicit ex: ScheduledExecutorService,
    ec: ExecutionContext): Future[T] = {
    delayedFuture(f, d).recoverWith {
      case e: Throwable => {
        if (t == 0) Failure(e).asInstanceOf[Future[T]]
        else repeatUntil(f, d, t - 1)
      }
    }
  }

其中d是尝试之间的延迟,t是最大尝试次数,delayedFuture使用提供的ScheduledExecutorService执行f延迟d。我担心如果t很大并且进行了很多(数千次)不成功的尝试,这有可能导致堆栈溢出,从而导致非常深的调用堆栈。如何在不消耗大量堆栈的情况下实现此目的,但最大限度地遵循函数式编程原则?

0 个答案:

没有答案