11

我正在向远程服务器发出请求,有时由于网络不可靠而请求失败。如果失败,我希望请求重复,但n次数最多。如果我使用命令式语言,我会将请求发送代码放在一个 while 循环中,但我想以一种功能性的方式来做。

我为此目的编写了助手:

/** Repeatedly executes function `f` 
  * while predicate `p` holds
  * but no more than `nTries` times.
  */
def repeatWhile[A](f: => A)(p: A => Boolean)(nTries: Int): Option[A] =
  if (nTries == 0) {
    None
  } else {
    f match {
      case a if p(a) => repeatWhile(f)(p)(nTries - 1)
      case a         => Some(a)
    }
  }

并像这样使用它:

// Emulating unreliable connection
var n = 0
def receive(): Option[String] =
  if (n < 4) {
    n += 1
    println("No result...")
    None
  } else {
    println("Result!")
    Some("Result")
  }

// Repeated call
val result = repeatWhile(receive)(!_.isDefined)(10)

wherereceive是用于测试目的的愚蠢功能。receive此代码在最终成功之前进行了 4 次调用Some(Result)

No result...
No result...
No result...
No result...
Result!

我的repeatWhile作品很好,但我想重新发明轮子。我正在学习函数式编程,想知道我的问题是否有简单/标准的解决方案。

Ps我已经定义了更多的助手,也许他们已经在语言/标准库中了?

/** Repeatedly executes function `f` 
  * while predicated `p` not holds
  * but no more than `nTries` times.
  */
def repeatWhileNot[A](f: => A)(p: A => Boolean)(nTries:Int): Option[A] = 
  repeatWhile(f)(!p(_))(nTries)

/** Repeatedly executes function `f` 
  * while it returns None 
  * but no more than `nTries` times.
  */
def repeatWhileNone[A](f: => Option[A])(nTries:Int): Option[A] = 
  repeatWhileNot(f)(_.isDefined)(nTries).getOrElse(None)
4

1 回答 1

16

规范的方法是使用Iterator

Iterator.continually{f}.take(nTries).dropWhile(!p).take(1).toList

这将为您提供一个空列表或单项列表,具体取决于它是否成功。headOption如果您愿意,可以将其转换为选项。稍作修改,这适用于您的所有用例。

正如您所做的那样编写小型递归方法也是非常明智的,尽管它们不在库中。一般来说,为你最常做的事情编写辅助方法是一个非常好的主意。这就是为什么 Scala 让编写方法变得如此容易的原因之一。

于 2012-07-07T18:32:18.387 回答