Adding through recursion

Donn Cave donn at u.washington.edu
Fri Nov 18 17:41:17 EST 2005


In article <dllhgj$mt0$1 at rose.polar.local>,
 Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:

> martin.clausen at gmail.com <martin.clausen at gmail.com> wrote:
> > def add(x, y):
> >     if x == 0:
> >         print y
> >         return y
> >     else:
> >         x -= 1
> >         y += 1
> >         add(x, y)
...
>     def recursive_add(x, y):
>         if x == 0:
>             print y
>             result = y
>         else:
>             x -= 1
>             y += 1
>             result = recursive_add(x, y)
>         return result
> 
> I find this much less error-prone than hiding return statements in
> branches throughout the function; if the only return statement is at
> the very end of the function, it becomes much easier to read.

Well, it's sure clearer where it returns.  On the other
hand, now you have to analyze the block structure to
know that the 3rd line assignment is still going to be
in effect when you get to the return.  That's easy in
this case, of course, but make the structure more complex
and add a loop or too, and it can be hard.  Where if you
see a return statement, you know for sure.

State variables are analogous to goto in a way, similar
sort of spaghetti potential.  It may or may not help to
have all the strands come out at the same spot, if the
route to that spot could be complicated.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list