Scala的懒惰论点:它们如何工作? [英] Scala's lazy arguments: How do they work?

查看:47
本文介绍了Scala的懒惰论点:它们如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解析器组合器库的Parsers.scala(Scala 2.9.1)文件中,我似乎遇到了一个鲜为人知的Scala功能,称为惰性参数".这是一个示例:

In the file Parsers.scala (Scala 2.9.1) from the parser combinators library I seem to have come across a lesser known Scala feature called "lazy arguments". Here's an example:

def ~ [U](q: => Parser[U]): Parser[~[T, U]] = { lazy val p = q // lazy argument
  (for(a <- this; b <- p) yield new ~(a,b)).named("~")
}

显然,在这里将调用名字参数q分配给惰性val p时发生了一些事情.

Apparently, there's something going on here with the assignment of the call-by-name argument q to the lazy val p.

到目前为止,我还无法弄清楚它的作用以及它为什么有用.有人可以帮忙吗?

So far I have not been able to work out what this does and why it's useful. Can anyone help?

推荐答案

按名称调用参数在每次您请求时都会被称为 .第一次将懒值称为 ,然后存储该值.如果再次要求,您将获得存储的值.

Call-by-name arguments are called every time you ask for them. Lazy vals are called the first time and then the value is stored. If you ask for it again, you'll get the stored value.

因此,像

def foo(x: => Expensive) = {
  lazy val cache = x
  /* do lots of stuff with cache */
}

是最终可行的,只要有可能并且只能一次完成的工作模式.如果您的代码路径根本不需要您使用x,那么它将永远不会得到评估.如果您需要多次,则只会对其进行一次评估并存储以备将来使用.因此,您可以保证进行零次(如果可能)或一次(如果不是)的昂贵通话.

is the ultimate put-off-work-as-long-as-possible-and-only-do-it-once pattern. If your code path never takes you to need x at all, then it will never get evaluated. If you need it multiple times, it'll only be evaluated once and stored for future use. So you do the expensive call either zero (if possible) or one (if not) times, guaranteed.

这篇关于Scala的懒惰论点:它们如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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