简体   繁体   English

按值和按名称的对等

[英]Call-by-value and by-name equivalence

I'm working in a Coursera course on functional programming and at some point they discuss the difference between call-by-value and call-by-name evaluation techniques. 我正在Coursera函数编程课程中工作,有时他们会讨论按值调用和按名称调用评估技术之间的区别。 They're some point that confuses me, they say: 他们说这是令我困惑的一点:

Both techniques reduce to the same final values as long as: 只要满足以下两种条件,这两种技术都会减少到相同的最终值:

  1. the reduced expressions consists of pure functions and 约简表达式由纯函数和
  2. both evaluations terminate 两次评估均终止

which seems to be a lambda calculus theorem. 这似乎是λ演算定理。

Could you explain me what they mean by "the reduced expressions conssist of pure functions"? 您能否解释一下“简化表达式由纯函数组成”是什么意思?

A pure function is one which has no side-effects (such as doing IO or changing any value not local to the function). 纯函数是没有副作用的函数(例如执行IO或更改函数本地以外的任何值)。 An example of a pure function would be: 一个纯函数的示例是:

def inc(x: Int) = x+1

An example of an impure function would be: 不纯函数的一个示例是:

var sum = 1
def addToSum(x: Int) = {
    sum += x
    sum
}

So now let's consider the following two methods, which only differ by whether they take their arguments by name or value: 因此,现在让我们考虑以下两种方法,它们的区别仅在于它们是使用名称还是使用值作为参数:

def doubleByValue(x: Int) = x + x
def doubleByName(x: =>Int) = x + x

Now if we use both of these with the pure function, the result is the same: 现在,如果我们将这两个函数与pure函数一起使用,则结果是相同的:

doubleByValue(inc(2)) // => 6
doubleByName(inc(2)) // => 6

But if we apply them to the impure function, the result differs: 但是,如果将它们应用于不纯函数,结果将有所不同:

sum = 1 // Let's reset sum, so the result isn't affected by previous uses
doubleByValue(addToSum(2)) // => 6, the value of `sum` is now 3
sum = 1 // Let's reset sum, so the result isn't affected by previous uses
doubleByName(addToSum(2)) // => 8, the value of `sum` is now 5

The difference is that the ByName version calls the function twice and adds the two results, whereas the ByValue version calls it once, saves the result and adds it to itself. 区别在于ByName版本调用该函数两次并添加两个结果,而ByValue版本调用一次,保存结果并将其添加到自身。

For the pure function this makes absolutely no difference - given the same argument, it will always return the same result, so it makes no difference whether you call it once and use the saved result twice or you call it twice (except for performance). 对于纯函数,这绝对没有区别-给定相同的参数,它将始终返回相同的结果,因此,无论是调用一次还是使用保存的结果两次还是调用两次(性能除外)都没有区别。

For the impure function it makes a big difference as the value of the sum variable is changed each time the function is called. 对于不纯函数,每次调用函数时sum更改sum变量的值,因此差异很大。

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

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