[Tutor] Cannot Understand

Anna Ravenscroft annaraven at gmail.com
Sat Mar 11 02:27:07 CET 2006

On 3/10/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> >> Could you please explain this code?.
> >>
> >> f = lambda n: n-1 + abs(n-1) and f(n-1)*n or 1
> >
> > This is why lambdas are evil.
> It's not the lambda thats evil its the need in Python to limit
> them to a single expression.
> If we write
> def f(n):
>    return n-1 + abs(n-1) and f(n-1)*n or 1
> its just as obscure.

Someone writing a named function is less likely to feel constrained to do an
obscure "one-liner".

if we write
> def f(n)
>    if not ((n-1) + abs(n-1)):
>       return f(n-1) * n
>    else return 1
> it gets a little clearer. And the only time the if expression
> is false is when n is zero or 1 so for the last time:
> def f(n)
>    if  n >1:
>       return f(n-1) * n
>    else:
>       return 1

This, is clear, and the  kind of thinking that, imho, writing an actual
function promotes. The other useful thing with this is: if you give it real
name instead of an anonymous, meaningless f, you can actually call the
function from other modules, or reuse it in other programs. Meaningful
naming also enhances readability. How much did we all have to go through to
figure out that this was a factorial function. What if, instead, it had
actually been given a real name, like, say "factor"... No need to work
through the complex code just to figure out what it was for.

In fact its the factorial function in very strange disguise!
> If we could write the lambda as
> f = lambda n:
>    if n>1:
>       return f(n-1) * n
>    else return 1
> is it so much more complex?
> > Officially, they are for creating "anonymous functions";
> > usually they only succeed in creating obscure unreadable drek.
> Unfortunately that's true. But as a concept they are a fundamental
> part of computing science and its hard to understamnd higher order
> programming or explore predicate calculus without them
> They are also of course very useful as shortcuts but thats usually
> where the cryptic code comes in.

Precisely. They are used as shortcuts and usually are far too clever by
half. I've seen a few people like you who use them clearly; unfortunately,
that's not the norm.

> In My Humble Opinion.
> And in mine, of course :-)

Well - the nice thing is that we both get to be right! ;-) And I think it's
useful to get the pros and cons out occasionally where newbies can see that
we don't all agree on everything, but that we can disagree politely and
still be helpful.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060310/7913c1a3/attachment.htm 

More information about the Tutor mailing list