|
|
|
Evaluation Order
Concerns when an actual parameter is evaluated to be assigned to a
formal parameter.
There are several options
- eager - evaluate at point of call
- lazy - evaluate only when first needed, cache result and use cached value
thereafter, also known as call-by-need (Miranda)
- normal-order - evaluate whenever needed, re-evaluate again and again.
Let's look at some examples. First eager evaluation.
{C - eager}
void infinite_loop() {
while (1);
}
void compute (int i, int j, int k) {
i = 2;
printf("i is %d, j is %d", i, j);
}
int x = 1;
int y = 2;
compute(x, y, 0); /* outputs 'i is 2, j is 2' */
int a[2] = (1, 2);
compute(x, a[x], 0); /* outputs 'i is 2, j is 1' */
compute(x, a[x], infinite_loop()); /* does not terminate!!! */
Here's a lazy evaluation example
{pseudo C - assume lazy evaluation}
void infinite_loop() {
while (1);
}
/* k is not used in procedure, so is never evaluated! */
void compute (int i, int j, int k) {
i = 2;
printf("i is %d, j is %d", i, j);
}
int x = 1;
int y = 2;
int a[2] = (1, 2);
compute(x, a[0], infinite_loop()); /* outputs 'i is 2, j is 1' */
Scheme normally has eager evaluation.
> (define (one) (begin (display 'yes) 1))
#<unspecified>
> (one)
yes1
> (+ (one) (one))
yesyes2
> ; note that y is never used
> (define (two x y) x)
#<unspecified>
> ; if lazy evaluation is used, we should only see one display of 'one
> (two (one) (one))
yesyes1
> ; so Scheme has eager evaluation
But in some functions, Scheme has lazy evaluation!
> ; lazy evaluation
> (if (< 7 23) (display 'yes) (display 'no))
yes
> ; if Scheme had used eager it would have displayed 'yesno' or 'noyes'
A normal order evaluation example.
/* pseudo C - assume normal order evaluation */
void infinite_loop() {
while (1);
}
void compute (int *i, int j, int k) {
*i = 2;
printf("i is %d, j is %d", i, j);
}
int x = 1;
int y = 2;
compute(x, y, 0); /* outputs 'i is 2, j is 2' */
int a[2] = (1, 2);
compute(x, a[1], infinite_loop()); /* outputs 'i is 2, j is 2' */
compute(x, a[x], 0); /* outputs 'i is 2, j is ?' */
Order of evaluation of parameters
- lazy, normal - evaluate when used
- eager - sequence specified by language/implementation
- left-to-right (
max(x=0, x=1) would return 1)
- right-to-left (
max(x=0, x=1) would return 0)
- indeterminate (means programmers shouldn't write stupid code like this)
Source of Information
These lecture notes are based on Chapter 9 in "Programming Languages, 6ed"
by Robert Sebesta and Chapter 8 in
"Programming Language Concepts and Paradigms" by David Watt.
|