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.
}
;; 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))
4条答案
按热度按时间ffx8fchx1#
按需调用是按名称调用的备忘录版本(参见wikipedia)。
在call-by-name中,参数在每次使用时都被求值,而在call-by-need中,参数在第一次使用时被求值,并记录值,以便随后不需要重新求值。
g0czyy6m2#
按名称调用是一种参数传递方案,其中参数在使用时计算,而不是在调用函数时计算。下面是伪C中的一个示例:
字符串
使用参数表达式的当前值访问参数表达式时,将延迟计算参数表达式。
6yoyoihd3#
将此添加到上述答案中:
通过流上的SICP部分工作。它很好地解释了按名称调用和按需求调用。它还展示了如何在Scheme中实现这些。顺便说一句,如果你正在寻找一个快速的解决方案,这里是Scheme中实现的基本按需求调用:
字符串
示例运行:
型
djp7away4#
Scala中的 call-by-name 步骤示例:
字符串
你可以在这里阅读 call-by-name 策略和 call-by-value 策略之间的区别:
https://www.scaler.com/topics/call-by-name/
更多关于延迟评估(call-by-need)的信息,请点击这里:
https://medium.com/background-thread/what-is-lazy-evaluation-programming-word-of-the-day-8a6f4410053f的