我正在做一项家庭作业,要求我们用我们开发的某种语言(使用Scheme)实现一种名为"call by name“的评估策略。
我们得到了一个example in Scala,但我不明白“按名称调用”是如何工作的,以及它与“按需调用”有什么不同?
发布于 2010-06-03 10:44:09
Call-by-need是call-by-name的记忆版本(参见wikipedia)。
在call-by-name中,参数在每次使用时都会求值,而在call-by-need中,参数在第一次使用时就会求值,并记录下来的值,这样以后就不需要重新求值了。
发布于 2010-06-03 10:46:25
按名称调用是一种参数传递方案,其中参数在使用时求值,而不是在调用函数时求值。下面是一个用伪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.
}当使用参数表达式的当前值访问该参数表达式时,会延迟计算该参数表达式。
发布于 2010-06-03 13:09:20
将这个添加到上面的答案中:
通过SICP section on Streams进行操作。它很好地解释了call-by-name和call-by-need。它还展示了如何在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.https://stackoverflow.com/questions/2962987
复制相似问题