做一些N次或直到Scala满足条件 [英] Do something up to N times or until condition is met in Scala
问题描述
我有一些Scala代码应该为网络服务查询某个标记,然后将该标记与预期标记进行比较。我希望继续查询预期的令牌,直到找到它,或者直到我尝试了N次尝试失败为止。
以下是如何在Java-tacular时尚:
def keepLooking(expectedToken:String,maxTries:Int){
var attempts = 0
var token =
do {
Thread.sleep(试试* 1000)//不要通过调用太快来压倒服务! (尝试< = maxTries&&& token!= expectedToken)
token = makeSomeNetworkCall()
tries + = 1
} b
我想在功能上做得更多。我有一个想法:
1.to(maxTries)map {tryNum =>
Thread.sleep(tryNum - 1 * 1000)//不要通过调用太快来压倒服务!
makeSomeNetworkCall()
}存在(_ == expectedToken)
提出了两个问题:
$ b $ ol
map
是懒惰的,所以存在
应该将它短路,对吧?如果我在第二次通话中找到我的代币,我不想进行10次网络通话。
回答1:
<$ c $如果您将范围
转换为流
,则
)
//将打印
// 1
// 2
I have some Scala code that should query a network service for a certain token, then compare that token to an expected one. I want to keep querying for the expected token until I find it, or until I've made N unsuccessful attempts.
Here's how it could be done in a Java-tacular fashion:
def keepLooking(expectedToken: String, maxTries: Int) {
var tries = 0
var token = ""
do {
Thread.sleep(tries * 1000) // don't overwhelm the service by calling it too fast!
token = makeSomeNetworkCall()
tries += 1
} while (tries <= maxTries && token != expectedToken)
}
I'd like to do it more functionally. I have one idea:
1.to(maxTries) map { tryNum =>
Thread.sleep(tryNum - 1 * 1000) // don't overwhelm the service by calling it too fast!
makeSomeNetworkCall()
} exists (_ == expectedToken)
But this raises two questions:
map
is lazy, soexists
should short circuit it, right? I don't want to make 10 network calls if I find my token on the second call.- Is there a more idiomatic way to achieve what I want?
Answer to 1.:
map
is only lazy if you convert the Range
to a Stream
:
(1 to 10).toStream map (i => { println(i); i }) exists (_ == 2)
// will print
// 1
// 2
这篇关于做一些N次或直到Scala满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!