简体   繁体   English

将按名称参数传播到函数调用

[英]Propagating a by-name parameter to a function call

Inside the body of a function that has a "By-name" parameter "f", I want to call another function and pass that parameter inside it. 在具有“按名字”参数“ f”的函数的内部,我想调用另一个函数并将该参数传递给它。 Specifically, I want to pass a "block" of code inside my timeit function: 具体来说,我想在timeit函数中传递代码“块”:

def warmUpAndMeasure(f: =>Int) = {
  val minimumTimeTaken = common.utils.timeit(
    repeat = 20, 
    assertResult = Some(148848)) {
      f
    }
  println(s"Best execution took $minimumTimeTaken ms.")
}
warmUpAndMeasure { antFunctional.funcs.walk(1000,1000) }

Starting from the last line of the code, I call warmUpAndMeasure passing inside it a code block. 从代码的最后一行开始,我调用warmUpAndMeasure并在其中传递代码块。 warmUpAndMeasure is in turn supposed to pass that block into common.utils.timeit , but setting it up first so that it will repeatedly (20 times) call the passed in code block, verifying that each time it returns 148848, and reporting at the end, the minimum time taken to execute the block (out of all 20 times). warmUpAndMeasure ,将warmUpAndMeasure将该块传递到common.utils.timeit ,但首先进行设置,以便它将重复(20次)调用传入的代码块,并验证每次返回148848并在最后报告,即执行该块所花费的最短时间(全部20次)。

I am new to Scala, and so far, the only way I've found out to pass f as-is into timeit (and not call it!) - as you can see in the code above - is to write another nameless code block: { f } . 我是Scala的新手,到目前为止,我发现将f timeit传递给timeit的唯一方法是timeit (而不是调用它!)-如您在上面的代码中所见-是编写另一个无名代码块: { f } Is there any other way to specify that I want f to pass in, not be called at the invocation of timeit ? 还有其他方法可以指定我希望f传递,而不是在调用timeit调用吗?

EDIT : Clarifying - my code above works, but I am just asking whether there's a better way to "delay the evaluation" of parameter f other than writing another block (as I did). 编辑 :澄清-我上面的代码有效,但是我只是问是否有比写另一个块更好的方法来“延迟对参数f的求值”(如我所做的那样)。 Here's the code for my timeit , for reference: 这是我的timeit的代码,以供参考:

def timeit[A](repeat:Int=20, assertResult:Option[A] = None)(f: => A) = {
  val minimumTime = List.range(1,repeat+1).map {
    idx => {
      if (idx == 1)
        print("Benchmark iteration:     ")
      print("\b\b\b\b%4d" format idx)
      val startTime = System.currentTimeMillis
      val result = f
      var totalTime = System.currentTimeMillis - startTime
      assertResult match {
        case Some(value) => {
          try { assert(value == result) }
          catch { case e:AssertionError =>
            println("\nExpected:" + value + ", got:" + result) ; throw e
          }
        }
        case None => ()
      }
      totalTime
    }
  }.min
  print("\n")
  minimumTime
}

显然,我唯一缺少的是我可以在括号内传递f (谢谢@vptheron)。

common.utils.timeit(repeat = 20, assertResult = Some(148848))(f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM