gpt4 book ai didi

java - 当Java8使用引用透明性时

转载 作者:行者123 更新时间:2023-12-02 04:40:24 25 4
gpt4 key购买 nike

我们注意到 java 8 使用 Referential Transparency :

我测试了很多代码来检测这个RT,例如:

public class ReferentialTransparency {
public static int triple(int number) {
System.out.println(number);
try {
Thread.sleep(500);
} catch (Exception e) {

}
return number* 3;
}
public static void main(String[] args) {
List<Integer> vals=Arrays.asList(1,2,3,4,3);
System.out.println(vals.parallelStream()
.mapToInt(ReferentialTransparency::triple)
.sum());
}
}

控制台:

3
4
2
1
3
39

我注意到,即使有一个元素 3 出现了两次,Java 8 也会运行三重方法。

我的问题,正如 Istvan 所解释的那样:

Why doesn't the compiler optimize out the repeated call to triple(3) if triple is referentially transparent?

最佳答案

您的三重方法不是引用透明的,因为它既向控制台打印内容又 hibernate 。这些操作都不是参照透明的。事实上,(从代码中)检测编译器是否优化了对引用透明函数的任何调用是相当困难的,因为如果您添加一条 print 语句来检测它,那么根据定义,您的函数将不再是引用透明的。

<小时/>

请注意,在您提供给 的链接中,给出的引用透明度的定义为

A property of a function whereby an expression can be replaced by its (evaluated) value without affecting the meaning of the program.

您可以看出 triple 不是引用透明的,因为对例如的调用triple(2) 不等于 6,因为仅计算 6 不会打印任何内容或 sleep ,而 triple(2) 还将打印 2 到控制台并 hibernate 一秒钟。由于用 6 替换 triple(2) 会通过删除打印和 hibernate 来影响程序的含义,因此 triple 不是引用透明的。

关于java - 当Java8使用引用透明性时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23827801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com