11 April 2007

Continuation Demystified

Many claim on the Internet that they have simple and intutive explanation for the concept of continuation: a programming language concept in Computer Science. (get off you non-cs guys).
But they don`t. They show off that they are smarter by using niche words and phrases. I am a dumb guy, so let us understand it step by step slowly like all bone heads like me do. (Let us get together later to curse them for all the non intutive explanation they offer)

Functions retrun values. Well atleast in C yes they do. Let us look at the following code:

void add(long a, long b)
{
return (a+b);
}


Let us call it from another function:

void callAdd()
{
long result = add(1,2);
printf("%d", result);
return;
}

Sweet. Now what? Now let us answer a question. Why do we have to return a value frm add? What if we call another function with the result of add as the argument?

So:

void add(long a, long b)
{
printResult(a+b);
}

Let us write the new function:

void printResult(int result)
{
printf("%d", result);
return;
}

Let us now change the defnition of callAdd()

void callAdd()
{
add(1,2);
return;
}

Thus printResult() is now the computation remaining after addtion is performed and add calls it and add does not return the result. Okie we are close.

What if we tell add() which function to call and send result to, as part of its argument?

void add(long a, long b, printResult)
{
printResult(a+b);
}

So callAdd() becomes... (let us forget function pointers for a while and assume this works)

void callAdd(printResult)
{
add(1,2,printResult);
return;
}

To be continued............

No comments:

Post a Comment

Please leave a note about what you think about this write up. Thanks.