做一些N次或直到Scala满足条件 [英] Do something up to N times or until condition is met in Scala

查看:206
本文介绍了做一些N次或直到Scala满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些Scala代码应该为网络服务查询某个标记,然后将该标记与预期标记进行比较。我希望继续查询预期的令牌,直到找到它,或者直到我尝试了N次尝试失败为止。



以下是如何在Java-tacular时尚:

  def keepLo​​oking(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到10).toStream map(i => {println(i); i})exists(_ == 2)(b =

     
    //将打印
    // 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:

    1. map is lazy, so exists should short circuit it, right? I don't want to make 10 network calls if I find my token on the second call.
    2. 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆