MC logo

Pass-By-Name Implementation

  CSc 404 Documentation And Examples

This slide indicates how pass-by-name would be implemented. Here is the code for Jensen's Device given in lecture.
begin
	real procedure Sum(k, low, hi, ak);
		value low, hi;
		integer k, low, hi;
		real ak;

		begin
			real S; S := 0;
			for k := low step 1 until hi do
				S := S + ak;
			Sum := S
		end;
	Sum(i, 1, 10, arr[i]);
	Sum(j, -20, 20, j*j - 4*j + 2);
end;

An approximate translation of this into C might look something like this:

double Sum(int * (*k)(void), int low, int hi, double * (*ak)(void)) 
{
	double S = 0;

	for(*k() = low; *k() <= hi; ++(*k())) {
		S = S + *ak();
	}
	return S;
}

int i;
double arr[100];
int *thunk1(void)
{
	return &i;
}
double *thunk2(void)
{
	return &arr[i];
}
Sum(thunk1, 1, 10, thunk2);

int j;
int *thunk3(void)
{
	return &j;
}
double *thunk4(void)
{
	static double res;
	res = j*j - 4*j + 2;
	return &res;
}
Sum(thunk3, -20, 20, thunk4);