a = b = 1 just syntactic sugar?

Steven Taschuk staschuk at telusplanet.net
Mon Jun 9 18:36:50 CEST 2003


Quoth Nielson Family:
  [...]
> I never meant the factorial I wrote below to be a 'final' product.  
> Rather, it was a simple test to demonstrate that the self-reference 
> worked correctly.

Oh, indeed.  It tests and illustrates the technique very well.

> When you say that it's not clear, do you mean that it's not clear from a 
> functional programming perspective?  Are you saying it is better 
> implemented with def? 

I mean it's better implemented with def.  The self-reference
*itself* doesn't bother me at all -- it's the contortions needed
to get the base case of the recursion properly handled inside a
lambda, for example.

If you know the and/or trick for making (something like) a
conditional operator, then

    factorial = lambda x: x==0 and 1 or x*selfref.myself(x-1)

might be a touch clearer.  (A real conditional operator would be
better here, of course; we're lucky to have a base case of 1.)

This expression is *just* complex enough to be *almost*
unreadable, imho.  Adding code to check that x >= 0 (to raise an
exception rather than recurse infinitely) pushes it over the edge.
I extrapolate from this simple case, to suspect that any real-life
recursive function would be too complex for such an implementation
to be readable.

It's still quite clever, though.

  [...]
-- 
Steven Taschuk                               staschuk at telusplanet.net
"[T]rue greatness is when your name is like ampere, watt, and fourier
 -- when it's spelled with a lower case letter."      -- R.W. Hamming





More information about the Python-list mailing list