Re: How to exit out of a function ? what is try-catch-throw in terms of Program Counter
<gnuist006@gmail.com> wrote in message
news:1192913158.922454.108100@k35g2000prh.googlegroups.com...
I have some code like this:
(if (test)
(exit)
(do something))
or
(if (test)
( do something)
(exit))
Various levels of nestings.
I have several questions, basic to sophisticated.
(1) What is the lisp equivalent idiom for (exit) as in bash or
in C.
(2) What is the best practice to handle this kind of problems?
(3) What is the intermediate practice to handle this kind of
problems.
NOTE: I am really afraid of try-catch-throw. I have never been
able to understand it since it does not exist in C and I cant
really visualize the construct in terms of C. That is what my
brain can process. If you understand it so well, you can show
me how one would really implement that kind of construct in
C and then by extension I can see that kind of program flow
in LISP. Whether its imperative programming or functional,
beneath there is program counter and assembly. C is close
to machine so much that it is almost assembly. So understanding try-c-
t in C is equivalent to understanding at
the level of machine language.
I therefore take the liberty to crosspost in C and C++ groups.
C++ compilers that compile to C will produce C code something like this
C++
double safesqrt(double x)
{
if(x < 0)
throw "imaginary root";
return sqrt(x);
}
double foo()
{
if( pow( sqrt(-1), sqrt(-1)) != exp(-M_PI/2) )
printf("Stupid computer can't do basic maths\n");
}
int main(void)
{
try
{
foo();
}
catch(char * err)
{
printf("Sorry %s\n", err);
}
}
C
void * safesqsrt(int *type, double *ret, double x)
{
if(x < 0)
{
*type = CHARSTAR;
return "imaginary root";
}
* ret = sqrt(x);
return 0;
}
void *foo(int *type)
{
double temp;
void *throw;
int throwtype;
throw = safesqrt(&throwtype, &temp, -1.0);
if(throw)
{
*type - throwtype;
return throw;
}
/* etc */
}
int main(void)
{
char *throw;
int throwtype;
char *err;
throw = foo(&throwtype);
if(throw)
goto catch;
return 0;
catch:
switch(throwtype)
{
case CHARSTAR:
err = throw;
printf("Sorry %s\n", err);
break;
}
}
As you see it is totally impractical to try to do this in handwritten C
code for very long, though a compiler will happily chug through it. There
are in fact more subtleties - local objects in foo() and safesqrt() have to
be destroyed.
--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm