我正在尝试在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
很大并且进行了很多(数千次)不成功的尝试,这有可能导致堆栈溢出,从而导致非常深的调用堆栈。如何在不消耗大量堆栈的情况下实现此目的,但最大限度地遵循函数式编程原则?