什么是“按名称呼叫”?

问题描述 投票:15回答:3

我正在做一个家庭作业,我们被要求以我们开发的某种语言(使用Scheme)实施名为“按名称呼叫”的评估策略。

我们得到了一个example in Scala,但我不明白“按名称呼叫”的工作方式以及它与“按需呼叫”有何不同?

scala scheme lazy-evaluation evaluation
3个回答
26
投票

Call-by-need是一个按名称调用的memoized版本(参见wikipedia)。

在按名称调用时,每次使用时都会对参数进行求值,而在需要调用时,会在第一次使用时对其进行求值,并记录值,以便随后不需要重新求值。


11
投票

按名称调用是一个参数传递方案,其中参数在使用时进行评估,而不是在调用函数时进行评估。这是伪C中的一个例子:

int i;
char array[3] = { 0, 1, 2 };

i = 0;
f(a[i]);

int f(int j)
{
    int k = j;    // k = 0
    i = 2;        // modify global i
    k = j;        // The argument expression (a[i]) is re-evaluated, giving 2.
}

使用参数表达式的当前值访问时,将对参数表达式进行延迟计算。


2
投票

将此添加到上面的答案:

通过SICP section on Streams工作。它对按名称调用和按需调用提供了很好的解释。它还展示了如何在Scheme中实现它们。顺便说一句,如果您正在寻找快速解决方案,请在Scheme中实施基本的按需拨号:

 ;; Returns a promise to execute a computation. (implements call-by-name)
 ;; Caches the result (memoization) of the computation on its first evaluation
 ;; and returns that value on subsequent calls. (implements call-by-need)
 (define-syntax delay
    (syntax-rules ()
      ((_ (expr ...))
       (let ((proc (lambda () (expr ...)))
             (already-evaluated #f)
             (result null))
         (lambda ()
           (if (not already-evaluated)
               (begin
                 (display "computing ...") (newline)
                 (set! result (proc))
                 (set! already-evaluated #t)))
           result)))))

 ;; Forces the evaluation of a delayed computation created by 'delay'.
 (define (my-force proc) (proc))

示例运行:

> (define lazy (delay (+ 3 4)))
> (force lazy) 
computing ... ;; Computes 3 + 4 and memoizes the result.
7
> (my-force lazy) 
7 ;; Returns the memoized value.
© www.soinside.com 2019 - 2024. All rights reserved.