简体   繁体   English

scalac for Call-by-Name使用引用

[英]scalac for Call-by-Name use references

I have some function: 我有一些功能:

def f(x: Int) = x * x

and then I call it: 然后我称之为:

var y = 0
f { y += 1; y }

Bytecode generated for above code looks like: 为上面的代码生成的字节代码如下所示:

     0: iconst_0      
     1: istore_1      
     2: aload_0       
     3: iload_1       
     4: iconst_1      
     5: iadd          
     6: istore_1      
     7: iload_1       
     8: invokevirtual #18                 // Method f:(I)I
    11: pop           
    12: return

If I change function def f(x: Int) to represent Call-by-Name: 如果我改变函数def f(x:Int)来表示Call-by-Name:

def f(x: => Int) = x * x

generated bytecode for the same part of code looks like: 为代码的相同部分生成的字节码如下所示:

     0: new           #24                 // class scala/runtime/IntRef
     3: dup           
     4: iconst_0      
     5: invokespecial #28                 // Method scala/runtime/IntRef."<init>":(I)V
     8: astore_1      
     9: aload_0
     ....

My question is: 我的问题是:

Is it a rule that for Call-by-Name we oparate on references or it depends on semantic analysis phase in compilation? 对于Call-by-Name,我们是否可以在引用上进行操作,或者它依赖于编译中的语义分析阶段?

Actual parameters to by-name formal parameters are always packaged into a so-called "thunk" (the terminology goes all the way back to Algol in the 1960s) which makes it possible for there to be zero, one or more (any number) of evaluations of the expression that comprises the actual argument. 副名称形式参数的实际参数总是打包成一个所谓的“thunk”(术语在20世纪60年代一直回到Algol),这使得零,一个或多个(任何数字)成为可能对包含实际参数的表达式的评估。 The bit about multiple evaluations is significant if there are side-effects in that expression. 如果在该表达式中存在副作用,则关于多个评估的位是重要的。

The specific use of that "reference" has to do with the fact that code that will execute in the called function will have a side-effect on a local variable (literally, specifically a var ) in the calling method. 该“引用”的具体用法与以下事实有关:将在被调用函数中执行的代码将对调用方法中的局部变量(字面上,特别是var )产生副作用。 That is why the IntRef is involved. 这就是IntRef参与的原因。 A "ref" of one sort or another (depending on the type of the var that gets referenced in the actual parameter expression) will always be used in that circumstance. 在这种情况下,将始终使用一种或另一种“ref”(取决于在实际参数表达式中引用的var的类型)。 If no var is involved, the value is simply copied to the thunk. 如果不涉及var ,则将该值简单地复制到thunk。

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

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