简体   繁体   English

例外和参考透明度

[英]Exceptions and referential transparency

Reading "Functional Programming in Scala" and I'm a little confused by the section on exceptions not being referentially transparent. 阅读“Scala中的函数式编程”,我对有关异常不是引用透明的部分感到有些困惑。

The example given is 给出的例子是

def failingFn(i: Int): Int = {
  val y: Int = throw new Exception("fail!")
  try {
    val x = 42 + 5
    x + y
  }
  catch { case e: Exception => 43 }
}

So the argument given in the book is that y is not referentially transparent because if we substitute it into the body in the try block we get a different result than if just run the function directly. 因此,本书中给出的论点是y不是引用透明的,因为如果我们将它替换为try块中的body,我们会得到与直接运行函数不同的结果。 This doesn't make any sense to me because the entire function is non-terminating to begin with so what is the point of saying values within the function body are not referentially transparent? 这对我没有任何意义,因为整个函数从一开始就是非终止的,那么说函数体中的值是不是在引用上是透明的呢? The naive substitution in my mind would be as follows 我心中的天真替代如下

def failingFn(i: Int): Int = {
  val y: Int = throw new Exception("fail!")
  try {
    val x = 42 + 5
    x + ((throw new Exception("fail!")): Int)
  }
  catch { case e: Exception => 43 }
}

and that still fails with the same exception. 并且仍然以相同的异常失败。

Moreoever, y itself is a non-value (it can't directly be evaluated to a value) so what is the point of talking about referential transparency for such expressions? 此外, y本身是一个非值(它不能直接被评估为一个值),那么谈论这些表达式的引用透明度有什么意义呢? I suspect there is some kind of sleight of hand going on here so where exactly is my reasoning incorrect? 我怀疑这里有什么样的手法,所以我的推理到底是不正确的?

The point being made in the book is that, if it were truly referentially transparent, then you can remove the y variable entirely and replace it inside of the try/catch and you end up with different semantics. 本书中提到的一点是,如果它真的是引用透明的,那么你可以完全删除y变量并在try/catch替换它,最后你会得到不同的语义。

So, the point being made is that, in the case of exceptions, the point of evaluation for an exception matters. 因此,要点是,在例外的情况下,异常的评估点很重要。

Maybe you can argue that the two programs are not semantically the same because of the location of the evaluation is what actually matters here. 也许你可以争辩说这两个程序在语义上并不相同,因为评估的位置在这里真正重要。 If you make the y lazy , then the outcomes do not change. 如果你使y lazy ,那么结果不会改变。

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

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