Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Let's Talk About Lambda Functions!

241 views
Skip to first unread message

Britt A. Green

unread,
Jul 26, 2002, 12:59:28 PM7/26/02
to
So I know what lambda functions are, they're syntax and how they're used.
However I'm not sure *why* one would use a lambda function. What's the
advantage that they offer over a regular function?

Britt

--
"My mom says I'm cool."


Chris Liechti

unread,
Jul 26, 2002, 2:44:00 PM7/26/02
to
"Britt A. Green" <pyt...@experimentzero.org> wrote in
news:mailman.102770585...@python.org:

> So I know what lambda functions are, they're syntax and how they're used.
> However I'm not sure *why* one would use a lambda function.

Guido may have asked himself similar questions, considering the note on the
OSCON and EuroPython slides ;-)

> What's the
> advantage that they offer over a regular function?

you can define a lambda in an expression, while a "def" is a statement.
and that's probably all there it is. (lambdas have some constraints as they
can only be expressions, but thats a detail)

cause' lambdas are expresions, they are useful when writing functional
style programs.

map(lambda x,y:x+y, range(3), [7,8,5])

chris
--
Chris <clie...@gmx.net>

Alex Martelli

unread,
Jul 26, 2002, 3:26:21 PM7/26/02
to
Britt A. Green wrote:

> So I know what lambda functions are, they're syntax and how they're used.
> However I'm not sure *why* one would use a lambda function. What's the

No idea, really. Maybe something to do with shocks in one's childhood.

> advantage that they offer over a regular function?

Well, they do look more mysterious and arcane, and therefore, maybe,
make their proponents believe they're k00l. With a lambda you can
keep a function anonymous, which must have something of the same
attraction as writing anonymous letters. You can also squish a lot
of them together in weird ways to take advantage of the fact that
a lambda form is an expression. k00l, innit?

Normal functions are clear, simple, understandable, and regular,
therefore intolerably middle-class, ordinary, bourgeois, mundane.

And they can take up a WHOLE extra line, or *more*!!!, which is
obviously appalling waste of, well, of something or other, for sure.


Alex

Paul Rubin

unread,
Jul 26, 2002, 3:41:43 PM7/26/02
to
"Britt A. Green" <pyt...@experimentzero.org> writes:
> So I know what lambda functions are, they're syntax and how they're used.
> However I'm not sure *why* one would use a lambda function. What's the
> advantage that they offer over a regular function?

You can use them inside other expressions, e.g. suppose you want to
sort a bunch of strings starting with the second letter:

a = ['apple', 'banana', 'pear', 'watermelon']
a.sort(lambda x,y: cmp(x[1],y[1]))

=> ['banana', 'watermelon', 'pear', 'apple']

Without lambda, you'd have to define a separate named function:

def CompareOnSecondLetter(x,y): return cmp(x[1],y[1])
a = ['apple', 'banana', 'pear', 'watermelon']
a.sort(CompareOnSecondLetter)

There's a school of thought that says Python shouldn't have lambda
and you should have to use def and give every function a name, but
IMO that goes against the decision that functions are objects in
Python. Python isn't Fortran.

There's a middle ground that says the name "lambda" (which comes from
Lisp) wasn't a good choice and another name should have been used
instead, like maybe 'func', which does the same thing. I guess that's
reasonable. I'm used to lambda from Lisp but another name would
probably be less scary to non-Lisp-users.

John Roth

unread,
Jul 26, 2002, 3:59:01 PM7/26/02
to

"Britt A. Green" <pyt...@experimentzero.org> wrote in message
news:mailman.102770585...@python.org...
> So I know what lambda functions are, their syntax and how they're

used.
> However I'm not sure *why* one would use a lambda function. What's the
> advantage that they offer over a regular function?

They let you put short, one-time functions inline. In some
environments (Tkinter comes immediately to mind) there
are lots of places where short, one-line functions are useful.
Putting a short, one-time function inline aids readability,
(at least for people who regard lambdas as readable.)

IMO, if the function is of any significant length, or if it
duplicates functionality from elsewhere, it should be
named and written separately.

John Roth


Robb Shecter

unread,
Jul 26, 2002, 4:10:06 PM7/26/02
to
Alex Martelli wrote:
> Britt A. Green wrote:
>
>
>>So I know what lambda functions are, they're syntax and how they're used.
>>However I'm not sure *why* one would use a lambda function. What's the
>
>
> No idea, really. Maybe something to do with shocks in one's childhood.

Well put - ( reminds me of many conversations I've had with many perl
programmers over the years: substitute 'lambda' for one of any hundred
_neat_ perl features :-).

But to really answer you - I like lambdas and think lambdas can add
clarity because their scope directly reflects their 'scope'. (Make sense?)

Robb

Britt A. Green

unread,
Jul 26, 2002, 3:52:38 PM7/26/02
to
I guess that begs the question: what's the advantage of functional-style
programming? :)

--
"My mom says I'm cool."

Alex Martelli

unread,
Jul 26, 2002, 5:18:56 PM7/26/02
to
Robb Shecter wrote:

> But to really answer you - I like lambdas and think lambdas can add
> clarity because their scope directly reflects their 'scope'. (Make
> sense?)

Sorry, not to me. Take a typical bug sometimes posted here, such as:

for word in 'fee fie foo fum'.split():
Button(frame, command=lambda: print word)

The poster is typically nonplusses that all buttons print 'fum'.

Lambda's scope (or 'scope') has taken another victim.


Using a closure instead of the lambda:

def makeprinter(word):
def printword(): print word
return printword

for word in 'fee fie foo fum'.split():
Button(frame, command=makeprinter(word))

is one of several ways to make the bug disappear (another is to
use a "lambda word=word: print word" snapshot-trick, but that
seems to fly in the face of your liking lambda's "scope"...?).
Closures' "scopes" can be said to directly reflect what they
should reflect. I can't see how you can claim this for lambda.


Alex

Alex Martelli

unread,
Jul 26, 2002, 5:21:12 PM7/26/02
to
Britt A. Green wrote:

> I guess that begs the question: what's the advantage of functional-style
> programming? :)

Working with higher-order functions, closures, list comprehensions
and other approaches typical of functional programming often offers
clear, concise and powerful ways of expression.

But you don't need to pay the price of lambda's obscurity for that.


Alex

Michael Gilfix

unread,
Jul 26, 2002, 5:04:56 PM7/26/02
to
Now this one could start a flame war and the answer itself is
impenetrable, I'm sure. I assume you do know what functional
programming is... But a few key highlights to start you off in your
quest for why: proponents of FP believe the software to be much less
error prone and easier to maintain (as it's easier to track down
the source of bugs). Much of this stems from the fact that proper
functional programming makes the use of side-effects more difficult
and makes the general program flow much easier to follow; implied
iteration via the map() function, for example, reduces code clutter
and a possible error in the looping code. Functional programs also
tend to make use of the generate and test paradigm, one which can
offer the most straight-forward solution (not necessarily the most
efficient) in many situations.

However, functional vs. imperative can be a very religious thing.
But I'm sure most people here in this group, myself included, will
agree that functional stuff is a good thing and the functional style
of programming tends to lead to very concise, easy to maintain, and
readable code.

-- Mike

On Fri, Jul 26 @ 12:52, Britt A. Green wrote:
> I guess that begs the question: what's the advantage of functional-style
> programming? :)

--
Michael Gilfix
mgi...@eecs.tufts.edu

For my gpg public key:
http://www.eecs.tufts.edu/~mgilfix/contact.html

Alex Martelli

unread,
Jul 26, 2002, 5:26:23 PM7/26/02
to
Paul Rubin wrote:

> "Britt A. Green" <pyt...@experimentzero.org> writes:
>> So I know what lambda functions are, they're syntax and how they're used.
>> However I'm not sure *why* one would use a lambda function. What's the
>> advantage that they offer over a regular function?
>
> You can use them inside other expressions, e.g. suppose you want to
> sort a bunch of strings starting with the second letter:
>
> a = ['apple', 'banana', 'pear', 'watermelon']
> a.sort(lambda x,y: cmp(x[1],y[1]))
>
> => ['banana', 'watermelon', 'pear', 'apple']
>
> Without lambda, you'd have to define a separate named function:

Without lambda, you might be more tempted to do it right (a la DSU):

aux = [ (x[1], x) for x in a ]
aux.sort()
a[:] = [ x for __, x in aux ]

When you're sorting 4 items, it doesn't matter, but try -- not a
huge number -- just 400, say.


> There's a middle ground that says the name "lambda" (which comes from
> Lisp) wasn't a good choice and another name should have been used
> instead, like maybe 'func', which does the same thing. I guess that's
> reasonable. I'm used to lambda from Lisp but another name would
> probably be less scary to non-Lisp-users.

It's not an issue of syntax sugar as superficial as what keyword to
use. A REAL lambda, by any other name -- the ability to package up
ANY chunk of code, not just an expression -- might add power enough
to justify its existence. Today's lambda's just deadweight. And I
do _not_ say that as a "non-Lisp-user" (though it's been a LONG time
since I last used Lisp, or Scheme for that matter, in production use).


Alex

Paul Rubin

unread,
Jul 26, 2002, 6:01:20 PM7/26/02
to al...@aleax.it
Alex Martelli <al...@aleax.it> writes:
> It's not an issue of syntax sugar as superficial as what keyword to
> use. A REAL lambda, by any other name -- the ability to package up
> ANY chunk of code, not just an expression -- might add power enough
> to justify its existence. Today's lambda's just deadweight.

I agree that the current incarnation of lambda is deficient. I
think it should be strengthened so you can lambdafy arbitrary code,
not eliminated. The current version is better than nothing, though.

I don't see why the anti-lambda contingent doesn't want to also
get rid of anonymous scalar expressions. I mean,

a = b + (c * d)

the horror! Why not insist on naming the subexpressions, e.g.

temp = c * d
a = b + temp

Michael Gilfix

unread,
Jul 26, 2002, 6:34:27 PM7/26/02
to
If it were the case that 'arbitrary code' could be truly
'lambdafied', wouldn't it be safe to say that arbitrary code could
then be pickled as well? While I know GVR designed like lambda in
themselves, even if functions definition could have a true lambda
property, that might be rather beneficial...

-- Mike

On Fri, Jul 26 @ 15:01, Paul Rubin wrote:
> I agree that the current incarnation of lambda is deficient. I
> think it should be strengthened so you can lambdafy arbitrary code,
> not eliminated. The current version is better than nothing, though.

--

Carl Banks

unread,
Jul 26, 2002, 6:59:18 PM7/26/02
to
Alex Martelli wrote:
> Robb Shecter wrote:
>
>> But to really answer you - I like lambdas and think lambdas can add
>> clarity because their scope directly reflects their 'scope'. (Make
>> sense?)
>
> Sorry, not to me. Take a typical bug sometimes posted here, such as:
>
> for word in 'fee fie foo fum'.split():
> Button(frame, command=lambda: print word)
>
> The poster is typically nonplusses that all buttons print 'fum'.


I imagine it's more likely that the poster would be nonplussed that it
produced a syntax error. :)


--
CARL BANKS
http://www.aerojockey.com

Carl Banks

unread,
Jul 26, 2002, 7:14:01 PM7/26/02
to
Alex Martelli wrote:>
> Paul Rubin wrote:
>
>> "Britt A. Green" <pyt...@experimentzero.org> writes:
>>> So I know what lambda functions are, they're syntax and how they're used.
>>> However I'm not sure *why* one would use a lambda function. What's the
>>> advantage that they offer over a regular function?
>>
>> You can use them inside other expressions, e.g. suppose you want to
>> sort a bunch of strings starting with the second letter:
>>
>> a = ['apple', 'banana', 'pear', 'watermelon']
>> a.sort(lambda x,y: cmp(x[1],y[1]))
>>
>> => ['banana', 'watermelon', 'pear', 'apple']
>>
>> Without lambda, you'd have to define a separate named function:
>
> Without lambda, you might be more tempted to do it right (a la DSU):
>
> aux = [ (x[1], x) for x in a ]
> aux.sort()
> a[:] = [ x for __, x in aux ]
>
> When you're sorting 4 items, it doesn't matter, but try -- not a
> huge number -- just 400, say.

Two things:

First, this has a pitfall: if x is not sortable for some reason, then
the "right" way can throw an exception due to lexical ordering of
tuples. I encountered this when trying to sort classes that didn't
have a __cmp__ method. It seems that a better way is to use id(x) as
the second element and x as the third: (x[1], id(x), x)

Second, if you're going to do it right often, you might want to wrap
it up in a function like this:

def sort_the_right_way (f, a):
aux = [ (f(x), x) for x in a ]


aux.sort()
a[:] = [ x for __, x in aux ]

In which case, the temptation to use lambda returns:

sort_the_right_way (lambda x:x[1], a)

Carl Banks

unread,
Jul 26, 2002, 7:15:05 PM7/26/02
to
Britt A. Green wrote:
> So I know what lambda functions are, they're syntax and how they're used.
> However I'm not sure *why* one would use a lambda function. What's the
> advantage that they offer over a regular function?

It's for lazy people. I am a lazy person.

Feel free to never use it, if you don't want.

Steve Holden

unread,
Jul 27, 2002, 12:12:30 AM7/27/02
to
"Alex Martelli" <al...@aleax.it> wrote in message
news:41j09.125397$Jj7.2...@news1.tin.it...

> Robb Shecter wrote:
>
> > But to really answer you - I like lambdas and think lambdas can add
> > clarity because their scope directly reflects their 'scope'. (Make
> > sense?)
>
> Sorry, not to me. Take a typical bug sometimes posted here, such as:
>
> for word in 'fee fie foo fum'.split():
> Button(frame, command=lambda: print word)
>
> The poster is typically nonplusses that all buttons print 'fum'.
>
I would be nonplussed if that code even *compiled*, given that "print" is a
keyword and lambda takes an expression not a statement.

> Lambda's scope (or 'scope') has taken another victim.
>

This is not to say, of course, that newbies don't try to write exactly such
incorrect code, and this is probably one of the reasons why Guido continues
to suggest it's a wart (albeit one we're going to have to continue to live
with).

>
> Using a closure instead of the lambda:
>
> def makeprinter(word):
> def printword(): print word
> return printword
>
> for word in 'fee fie foo fum'.split():
> Button(frame, command=makeprinter(word))
>
> is one of several ways to make the bug disappear (another is to
> use a "lambda word=word: print word" snapshot-trick, but that
> seems to fly in the face of your liking lambda's "scope"...?).
> Closures' "scopes" can be said to directly reflect what they
> should reflect. I can't see how you can claim this for lambda.
>

not-like-you-to-propagate-syntax-errors-ly y'rs - steve
-----------------------------------------------------------------------
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------

Steve Holden

unread,
Jul 27, 2002, 12:16:07 AM7/27/02
to
"Paul Rubin" <phr-n...@NOSPAMnightsong.com> wrote in message
news:7x3cu6f...@ruckus.brouhaha.com...

k00l! Then we *could* use

(a)

to represent a single-element tuple.

that's-enough-ly y'rs - steve

Steve Holden

unread,
Jul 27, 2002, 12:19:03 AM7/27/02
to
"John Roth" <john...@ameritech.net> wrote in message
news:uk3abpr...@news.supernews.com...

And let us not forget that those who hate naming one-off functions can reuse
the names if they want.

def a(x):
print x
def a(y):
print y*y

is perfectly legal Python.

regards

Jeremy Bowers

unread,
Jul 27, 2002, 1:30:28 AM7/27/02
to
On Fri, 26 Jul 2002 16:18:56 -0500, Alex Martelli wrote:

> Robb Shecter wrote:
>
>> But to really answer you - I like lambdas and think lambdas can add
>> clarity because their scope directly reflects their 'scope'. (Make
>> sense?)
>
> Sorry, not to me. Take a typical bug sometimes posted here, such as:
>
> for word in 'fee fie foo fum'.split():
> Button(frame, command=lambda: print word)
>
> The poster is typically nonplusses that all buttons print 'fum'.

Speaking as one who recently posted this, what's the alternative?

for word in 'fee fie foo fum'.split():

def printThing():
print word
Button(frame, printThing)

doesn't work any better, you still need

for word in 'fee fie foo fum'.split():

def printThing(word = word):
print word
Button(frame, printThing)

Lambda wart, or just scoping wart in general?

(And I'll still take the lambda form; the def statement feels wrong here.)

Alex Martelli

unread,
Jul 27, 2002, 3:11:46 AM7/27/02
to
Jeremy Bowers wrote:
...

>> for word in 'fee fie foo fum'.split():
>> Button(frame, command=lambda: print word)
>>
>> The poster is typically nonplusses that all buttons print 'fum'.
>
> Speaking as one who recently posted this, what's the alternative?
>
> for word in 'fee fie foo fum'.split():
> def printThing():
> print word
> Button(frame, printThing)
>
> doesn't work any better, you still need
>
> for word in 'fee fie foo fum'.split():
> def printThing(word = word):
> print word
> Button(frame, printThing)

Not sure why you snipped the closure solution, which looks like
the obvious one to me once one has seen it:

def makePrinter(word):
def printit(): print word
return printit

for word in 'fee fie foo fum'.split():

Button(frame, command=makePrinter(word))


> Lambda wart, or just scoping wart in general?

Not sure if it qualifies as a "wart", just as a little trap which
is empirically observed to catch users of lambdas, not users of
named functions. I've never met anybody who expected the solution
with 'def' in the loop to somehow snapshot the values in the
surrounding environment (maybe I've just led a sheltered life?),
while several users of lambda seem to expect exactly that. Given
which, touting the appropriateness of lambda's scoping seems weird!


> (And I'll still take the lambda form; the def statement feels wrong here.)

Guess that's what wrong with having lambda in the language: without
adding any capability, it gives two ways to solve some problems, one
of which feels wrong to you, the other one of which IS wrong.

Because, you see, I put a little trap in this example... and it
seems to me that you fell right into it.

The lambda solution doesn't work. At all. It gives you a SyntaxError
if you try it!

lambda cannot include a statement. print is a statement. Oooops...!-)

So, if you structure your code with lambda, the moment you want
to add a print statement, boom -- can't do. You have to restructure
your code to use def instead. When you remove the print after it's
done its debugging-help job, will you restructure once again to
take the def away in favor of lambda... and again NEXT time you
need to have a statement there too, etc, etc...? What a lot of
purposeless code churning...!

Use def and avoid all of this silly self-imposed useless work.


Alex

Alex Martelli

unread,
Jul 27, 2002, 3:21:57 AM7/27/02
to
Steve Holden wrote:
...

>> for word in 'fee fie foo fum'.split():
>> Button(frame, command=lambda: print word)
>>
>> The poster is typically nonplusses that all buttons print 'fum'.
>>
> I would be nonplussed if that code even *compiled*, given that "print" is
> a keyword and lambda takes an expression not a statement.

Right - you caught my little trap. I don't regret using it, though,
because it DID catch a couple of lambda-lovers... and it also shows
a real issue with lambda. Sure, you get a SyntaxError and that's
that. But if you want to use lambda, you have to keep dismantling
and restructuring to change to def'd functions each time you need a
statement there (and print is a good example here, as it does help
debugging).


>> Lambda's scope (or 'scope') has taken another victim.
>>
> This is not to say, of course, that newbies don't try to write exactly
> such incorrect code, and this is probably one of the reasons why Guido
> continues to suggest it's a wart (albeit one we're going to have to
> continue to live with).

I think the reason why Guido suggests it's a wart is that it IS a wart.

Sure, backwards compatibility mandates lambda stay, but I think it's
worth emphasizing that it's there ONLY for backwards compatibility,
and using def is better.


> not-like-you-to-propagate-syntax-errors-ly y'rs - steve

Right. Inserting subtle traps in my examples, however, IS a think
I've been known to do. Sometimes it helps drive a point home.


Alex

Alex Martelli

unread,
Jul 27, 2002, 4:02:35 AM7/27/02
to
Carl Banks wrote:
...

>>> sort a bunch of strings starting with the second letter:
...

> First, this has a pitfall: if x is not sortable for some reason, then

...then x is not a string, therefore the specs ("sort a bunch of
strings starting with the second letter", as above quoted) do not
apply.

Actually, the sort-with-argument solution proposed by the original
poster didn't meet the OP's specs: it ONLY sorted on the second
letter, giving an unspecified ordering to strings whose second
letters are equal -- no "starting with". I read the specs as
meaning "as if each string started with its second letter and
then continued with the actual string", but one could read them
in other ways, e.g., sorting x[1:] (the slice that starts with
the second letter).

> the "right" way can throw an exception due to lexical ordering of
> tuples. I encountered this when trying to sort classes that didn't
> have a __cmp__ method. It seems that a better way is to use id(x) as
> the second element and x as the third: (x[1], id(x), x)

That would go back to unspecified ordering for strings with equal
second letters -- hardly sensible behavior. It's just as much (or
as little) effort, if you DO want the second letter to be the ONLY
(rather than STARTING) sort key, to get a STABLE sort:

aux = [ (x[i][1], i) for i in xrange(len(a)) ]
aux.sort()
a[:] = [ a[i] for __, i in aux ]

> Second, if you're going to do it right often, you might want to wrap
> it up in a function like this:
>
> def sort_the_right_way (f, a):
> aux = [ (f(x), x) for x in a ]
> aux.sort()
> a[:] = [ x for __, x in aux ]

You can do that, but then you risk 'freezing' in your higher order
function a suboptimal way to proceed -- e.g., no way this function
can be told to produce stable sorts, while keeping DSU inline it's
trivial to ensure the sort is stable.

The temptation to overgeneralize often accompanies the decision to
freeze some idiom into a higher-order function. Keeping the idiom
inline avoids temptations to overgeneralize. Thus, while it does
fly in the face of accepted wisdom, in Python sometimes it's wiser
to NOT refactor too many idioms and design patterns into ambitious
frameworks. It's an observation which Tim also makes in his
chapter intro in the Cookbook, by the way -- with Python it's often
simpler to code idiomatically than to learn and adopt a framework
ambitious enough to cover all needed cases. I would add the comment
that developing such frameworks is such child's play in Python, and
FUN, that one does it anyway -- even though they may not seem much
use afterwards:-).


> In which case, the temptation to use lambda returns:
>
> sort_the_right_way (lambda x:x[1], a)

Somebody ambitious enough to encapsulate DSU should surely proceed
by encapsulating typical accessors to be used with it in closure
factories, e.g.

sort_the_right_way(make_items_acessor((1,)), a)

thereby avoiding lambda again. It's only when stuff gets wrapped
at once too much (by freezing some subset of DSU into a higher
order function) AND not enough (by not supplying other higher
order functions to go with it by building needed closures) that
the _temptation_ of lambda'ing around perks up. Easily avoided
by noting that even in that case one more def does it, of course.

It takes one more line -- saving lines is probably the core
fetish of lambda-enthusiasts, after all. I propose again the
hypothesis that such obsession may be linked to traumas in
one's childhood...


Alex

Alex Martelli

unread,
Jul 27, 2002, 4:05:17 AM7/27/02
to
Michael Gilfix wrote:

> If it were the case that 'arbitrary code' could be truly
> 'lambdafied', wouldn't it be safe to say that arbitrary code could
> then be pickled as well?

I don't see any connection between the two issues. lambda form vs
a def statement is strictly a syntax issue. You cannot pickle a
lambda any more than you can pickle a function built by def.


Alex

Alex Martelli

unread,
Jul 27, 2002, 4:26:51 AM7/27/02
to
Paul Rubin wrote:

> Alex Martelli <al...@aleax.it> writes:
>> It's not an issue of syntax sugar as superficial as what keyword to
>> use. A REAL lambda, by any other name -- the ability to package up
>> ANY chunk of code, not just an expression -- might add power enough
>> to justify its existence. Today's lambda's just deadweight.
>
> I agree that the current incarnation of lambda is deficient. I

Great -- we do have one point of agreement. I fear it will be
the only one:-).

> think it should be strengthened so you can lambdafy arbitrary code,

So, invent a syntax that is nice, Pythonic (indentation etc), and
free of ambiguity and error-prone aspects. Me, I haven't managed
to, but that doesn't say much. It MAY be more significant that no
such wonderful syntax has ever been proposed (that I know of)
throughout the interminable debates over the years about lambda,
anonymous codeblocks, and other such themes.

> not eliminated. The current version is better than nothing, though.

Here's where we disagree. It adds no real ability to the language,
just little traps, pitfalls, annoyances and MTOWTDIs.


> I don't see why the anti-lambda contingent doesn't want to also
> get rid of anonymous scalar expressions. I mean,

"scalar"? What's "scalar" about it?

> a = b + (c * d)

This could perfectly well be a list expression -- concatenate
list b with c repetitions of list d (or, d repetitions of list
c). "scalar"...???

The parentheses above are redundant, of course. That may make
using them bad style, but allowing them in terms of language _rules_
is one of those MTOWTDIs we can never eliminate without ADDING
horrible complications to the syntax.

Hypothetically removing the production for lambda from the
syntax would of course, just as hypothetically, simplify the
syntax. Removing the ability to parenthesize EXCEPT where
the parentheses are significant would be a nightmare of
complexity for no real gain.

It's therefore rather silly to try to equate the two things.

> the horror! Why not insist on naming the subexpressions, e.g.
>
> temp = c * d
> a = b + temp

If there is further significant use of that c*d result later
on, giving it a name (though not one such as 'temp', most
likely, unless it's something's temperature I guess) might
be a good idea. If the intermediate result is insignificant
per se, then naming it would have no added value.

It's rarely the case that functions are insignificant. The
DO something, or COMPUTE something, which tends to make them
worth naming. A result of a multiplication, on the other hand,
IS something, and the verb "to be" is fraught with problems
(I summarize some of them, albeit in a different context, in
http://www.aleax.it/Python/5ep.html -- most significant are
the bibliographical pointers to the relevant works of
Santayana, Wittgenstein, and most relevantly Korzybski).

Summarizing: it's seldom the case that it's optimal to draw
attention to what something IS. It's often the case that it's
best to draw attention to what something DOES. Thus, naming
intermediate results that "just ARE" (results of such ops as
adding, multiplying, ...) is only interesting in quite specific
cases, basically when the thing you're naming has some domain
specific relevance. Naming objects that "DO", i.e., functions,
is more often advisable.

If in one case in a thousand there's some slight advantage
to not-naming a doer, that doesn't mean lambda is pulling
its weight -- it's still deadwood, not worth the downsides.


Alex


John Roth

unread,
Jul 27, 2002, 8:20:20 AM7/27/02
to

"Steve Holden" <sho...@holdenweb.com> wrote in message
news:Lap09.24994$724....@atlpnn01.usenetserver.com...

It took me a moment to realize what you were getting at. Granted,
it's perfectly legal Python, but the first def is rebound by the second,
so it has absolutely no effect unless (and this is what wasn't obvious
from the example) it's bound to something else before the second
definition.

Also, that's probably going to confuse lots of software. I'd suspect
that most class browsers, if they found six methods with the same
name in a class, would report either the first or the last, or else
flag it as an error.

John Roth

Jeremy Bowers

unread,
Jul 27, 2002, 10:34:17 AM7/27/02
to
On Sat, 27 Jul 2002 02:11:46 -0500, Alex Martelli wrote:

> Jeremy Bowers wrote:

> Not sure why you snipped the closure solution, which looks like
> the obvious one to me once one has seen it:

Oops, sorry, too late. I ended up scrolling over it.

>> (And I'll still take the lambda form; the def statement feels wrong here.)
>
> Guess that's what wrong with having lambda in the language: without
> adding any capability, it gives two ways to solve some problems, one
> of which feels wrong to you, the other one of which IS wrong.

Fair enough.

> Because, you see, I put a little trap in this example... and it
> seems to me that you fell right into it.

Yes and no... I never wrote a lambda myself that had a print in it. I know
you can't do that, and others had already commented on it.

I almost always use a print function of my own devising, so I _can_ use
print in a lambda.

(That's not why I wrote that function though; I like emacs as my
coding environment, but you get all the output and error tracebacks all at
once, as a lump when you close the program, if it's a Tk program. I have
a print function that can go over the network, or to console, or to
nowhere at all.)

> Use def and avoid all of this silly self-imposed useless work.

I already don't use "print" so perhaps that part of the reason it doesn't
bother me. (Note I'm not proposing this is a solution everyone should
seek, just that it may explain my ambivilence on the issue.)

Carl Banks

unread,
Jul 27, 2002, 1:52:08 PM7/27/02
to
Alex Martelli wrote:

> Carl Banks wrote:
>> Second, if you're going to do it right often, you might want to wrap
>> it up in a function like this:
>>
>> def sort_the_right_way (f, a):
>> aux = [ (f(x), x) for x in a ]
>> aux.sort()
>> a[:] = [ x for __, x in aux ]
>
> You can do that, but then you risk 'freezing' in your higher order
> function a suboptimal way to proceed -- e.g., no way this function
> can be told to produce stable sorts, while keeping DSU inline it's
> trivial to ensure the sort is stable.
>
> The temptation to overgeneralize often accompanies the decision to
> freeze some idiom into a higher-order function. Keeping the idiom
> inline avoids temptations to overgeneralize. Thus, while it does
> fly in the face of accepted wisdom, in Python sometimes it's wiser
> to NOT refactor too many idioms and design patterns into ambitious
> frameworks.

Come on! Wrapping up a sort in a function is an "ambitious
framework"? I'm talking about writing a single function because a
certain sort appears a dozen or so times in the code. I'm sure you're
aware of the advantages of putting oft-repeated code into one place.

If you need another kind of sort for some reason, just don't use the
function.


[snip]


>
>> In which case, the temptation to use lambda returns:
>>
>> sort_the_right_way (lambda x:x[1], a)
>
> Somebody ambitious enough to encapsulate DSU should surely proceed
> by encapsulating typical accessors to be used with it in closure
> factories, e.g.
>
> sort_the_right_way(make_items_acessor((1,)), a)
>
> thereby avoiding lambda again. It's only when stuff gets wrapped
> at once too much (by freezing some subset of DSU into a higher
> order function) AND not enough (by not supplying other higher
> order functions to go with it by building needed closures) that
> the _temptation_ of lambda'ing around perks up. Easily avoided
> by noting that even in that case one more def does it, of course.

So now you're advocating building a framework of closures to replace
the lambdas? This is what appears odd to me: you want me to inline
sorts in the interest of not overgeneralizing, but it seems the same
can be said by your use of make_items_accessor above.

I have good reasons for my choice of where I generalize. I've never
needed to be particular about the order of equal items; indeterminate
is fine for me. One way to sort has sufficed for my whole life, thus,
it makes sense for me to generalize. OTOH, I rarely have a use for
generalizing x[1], so I would not bother with a closure. Even if I
hated lambdas, I would just write:

def second(x): return x[1]

(Of course, I'll write the closure if the need ever comes to have the
program select the index.)

What I'm saying is, your objection that this use of lambda only is
necessary because of over- and under-generalizatino isn't true for my
circumstances.


> It takes one more line -- saving lines is probably the core
> fetish of lambda-enthusiasts, after all. I propose again the
> hypothesis that such obsession may be linked to traumas in
> one's childhood...

Personally, I don't care about saving lines, per se. For me, lambda
helps me to avoid stopping mid-function call, scrolling many or few
lines to implement the function as a def, and returning. I.e.,
lambdas save me cursor movement.

Fredrik Lundh

unread,
Jul 27, 2002, 3:15:55 PM7/27/02
to
Carl Banks wrote:

> So now you're advocating building a framework of closures to replace
> the lambdas? This is what appears odd to me: you want me to inline
> sorts in the interest of not overgeneralizing, but it seems the same
> can be said by your use of make_items_accessor above.

don't feed the troll.

</F>


Carl Banks

unread,
Jul 27, 2002, 4:02:20 PM7/27/02
to

I'm sorry, I didn't realize Martelli was trolling. I'll try not to
feed him. :)

Seriously, no offense was intended. When he suggested using a wrapper
function like make_items_accessor, after advising against a wrapper
for sorts because of overgeneralization concerns, it rightly seemed
odd to me (especially since I tend to do the opposite), and I wanted
to point that out. That point is, overgeneralization concern itself
is not good enough reason to avoid wrapping a function or building a
framework, without more information about the circumstances.

I'm sorry if it seemed like I was trolling.

Fredrik Lundh

unread,
Jul 27, 2002, 4:17:55 PM7/27/02
to
Carl Banks wrote:

> I'm sorry if it seemed like I was trolling.

Oh, sorry, I didn't mean you. I meant the "lambda lovers have
childhood traumas" guy. If he cannot defend his position with-
out stuff like that, it must be a pretty worthless position.

If you like lambdas, use them. All the best pythoneers do, so why
shouldn't you?

And as you noted, they're great when you need something simple,
and don't want to break the flow. And when you find that you have
to refactor, it's not that hard to turn that comment into a def line,
add a newline and type "return".

(Premature refactoring is the root of all evil, etc. ;-)

Oops, my typometer just rolled over. time to stop worki


Alex Martelli

unread,
Jul 27, 2002, 4:25:18 PM7/27/02
to
Carl Banks wrote:
...
>>> def sort_the_right_way (f, a):
...

> Come on! Wrapping up a sort in a function is an "ambitious
> framework"? I'm talking about writing a single function because a
> certain sort appears a dozen or so times in the code. I'm sure you're
> aware of the advantages of putting oft-repeated code into one place.

If the SAME sort appears repeatedly, it surely needs to be a
function. But you do have to get your parameters right when
"same" is not exactly "same". And if it gets to...:
...


>>> sort_the_right_way (lambda x:x[1], a)

...the lambda suggests imperfect factorization. If this "same" sort
does occur often, IS it the case that this is the ONLY place where it
needs to be by the 1-th item? Or, by AN item?

Statistically, it IS possible that the sort is both frequent enough
to deserve factoring out AND yet so varied and diverse in the criteria
to use that a general function is the only effective way to express
them AND that this one in particular is a freak case never to reoccur,
so that naming the sortfield-selector function (while not a problem)
MIGHT be fractionally suboptimal.

The combination of each of these unlikely factors, all together,
multiplies down to a VERY small chance. And naming the sort selector
function is such a TINY "cost" to pay (come on, now, HOW horrible is
it to have to name even such a function as the above one?), even in
the extremely unlikely case that it IS a cost at all (rather than,
as far more likely, a benefit), that *lambda is not pulling its own
weight in the language*. It cannot, hobbled as it is: it's a wart,
deadweight, better forgotten.


>> Somebody ambitious enough to encapsulate DSU should surely proceed

...


> So now you're advocating building a framework of closures to replace

No, I'm saying that IF somebody was ambitious enough to encapsulate
DSU, then the same somebody should be consistent and proceed along
the same route. "If the fool would persist in his folly he would
become wise" (Blake). Can't you read?

> hated lambdas, I would just write:
>
> def second(x): return x[1]

If that's what you need, fine.

> (Of course, I'll write the closure if the need ever comes to have the
> program select the index.)
>
> What I'm saying is, your objection that this use of lambda only is
> necessary because of over- and under-generalizatino isn't true for my
> circumstances.

I don't know you well enough to use my judgment about your specific,
individual circumstances, but I *DO* know that I *NEVER* said, implied,
inferred or let it be suspected that "this use of lambda is
*NECESSARY*" (my emphasis). It obviously *ISN'T* _necessary_, as
your hypothetical function "second" shows. You DO know what
"necessary" means, yes? It's a MUCH stronger word than, say,
"opportune". What an extremely unlikely combination of circumstances
MIGHT cause (and I cannot rule out that your personal, individual
circumstances might be exactly those), are cases in which lambda
is *vaguely defensible* -- never necessary, but if every single one
of those circumstances (and more yet, such as, no need ever to stray
from the confines of what can comfortably be put in an expression)
obtained, then using lambda wouldn't be totally absurd.

It still would be INFERIOR (e.g., debugging would be harder as
the traceback would not identify the failing extractor by name,
as 'second', but only anonymously as 'lambda' -- who lives by
the sword [of anonymity]...), but not absurdly so.

But it's far simpler to never use lambda, than to analyze each
case to ascertain whether it's absurd or merely inferior to use
it in any single given case. Great saving of energy, to have
one less "way to do it" when that "way" is such a loser.


> Personally, I don't care about saving lines, per se. For me, lambda
> helps me to avoid stopping mid-function call, scrolling many or few
> lines to implement the function as a def, and returning. I.e.,
> lambdas save me cursor movement.

In VIM, I hit ESC, uppercase-O, and I'm in insert mode on a newly
inserted immediately-previous line with correct indent, ready to
flow on with def and so on. I assume more powerful editors and
IDEs, such as EMACS and the like, must have facilities at least as
powerful. Thus, the "saving" seems utterly trivial.


Alex

Alex Martelli

unread,
Jul 27, 2002, 4:50:50 PM7/27/02
to
Fredrik Lundh wrote:

> Carl Banks wrote:
>
>> I'm sorry if it seemed like I was trolling.
>
> Oh, sorry, I didn't mean you. I meant the "lambda lovers have
> childhood traumas" guy. If he cannot defend his position with-
> out stuff like that, it must be a pretty worthless position.

I can defend my position, or attack yours, in many different
ways, but I've noticed that ways that tend to elicit smiles
(albeit delivered in my usual deadpan style) also tend to stick
better and more effectively in many humans' minds. Haven't
you noticed the same effect in your occasional, wry attempts
at humor?


> If you like lambdas, use them. All the best pythoneers do, so why
> shouldn't you?

On the other hand, implied put-downs such as this one (which
logically implies "if you don't use lambdas, you're not among
the best pythoneers") are only effective if they're allowed to
operate subliminally; once brought to light as bullying attempts,
they lose most of their effectiveness.

Alex

Fredrik Lundh

unread,
Jul 27, 2002, 5:18:18 PM7/27/02
to
(reset)

Alex Martelli wrote:

> I can defend my position

well, unless it's some variation of "gotta keep arguing", I'm not
really sure what your position is.

> > If you like lambdas, use them. All the best pythoneers do, so why
> > shouldn't you?
>
> On the other hand, implied put-downs such as this one

it's an observation based on grep + a considerable amount of
freely available code...

...cannot judge code that I haven't seen, though. so feel free
to consider yourself a great pythoneer, even if the strakt code-
base is completely free from lambdas and print >> etc.

</F>


Carl Banks

unread,
Jul 27, 2002, 5:45:02 PM7/27/02
to

Not for me. I have found this "very small chance" you speak of to be
common in my programming, although not for sorting. I pass functions
around a lot, both by preference, and because it is useful for the
programs I write (a lot of deeply nested and arbitrary structure).

So yes, when I've done this, it has been proper factorization. It's
certainly been more ideal than repeating lots of similar "global"
operations that vary only in the "local" operation.


[snip]


>>> Somebody ambitious enough to encapsulate DSU should surely proceed
> ...
>> So now you're advocating building a framework of closures to replace
>
> No, I'm saying that IF somebody was ambitious enough to encapsulate
> DSU, then the same somebody should be consistent and proceed along
> the same route. "If the fool would persist in his folly he would
> become wise" (Blake). Can't you read?

Evidently not. Sorry about that.

You're wrong, though. As I've said, I have good reason to wrap up my
sort functions, but no such good reason to wrap up functions I pass to
it that way. As I've said, I pass around all kinds of functions, and
that is where I face danger of trying to overgeneralize.


[snip]


>> What I'm saying is, your objection that this use of lambda only is

>> necessary because of over- and under-generalization isn't true for my


>> circumstances.
>
> I don't know you well enough to use my judgment about your specific,
> individual circumstances, but I *DO* know that I *NEVER* said, implied,
> inferred or let it be suspected that "this use of lambda is
> *NECESSARY*" (my emphasis).

Again, I'm sorry. I misspoke. If I replace necessary with tempting,
is that what you were objecting? (Or were you objecting that the
tempation to use lambda was because of the over- and
under-generalization?)

Well, whatever. All I'm saying is, for me, with the way I organize
and factor code, the situation where it is tempting to use lambda
comes up a lot, and not because of any over- or under-generalization
on my part.


[snip]


>> Personally, I don't care about saving lines, per se. For me, lambda
>> helps me to avoid stopping mid-function call, scrolling many or few
>> lines to implement the function as a def, and returning. I.e.,
>> lambdas save me cursor movement.
>
> In VIM, I hit ESC, uppercase-O, and I'm in insert mode on a newly
> inserted immediately-previous line with correct indent, ready to
> flow on with def and so on. I assume more powerful editors and
> IDEs, such as EMACS and the like, must have facilities at least as
> powerful. Thus, the "saving" seems utterly trivial.

It's not about keystrokes. Stopping mid-function-invocation to define
a function stops my train of thought, one way or another. Regaining
my train of thought, and my cursor position, is what I find tiring.

Michele Simionato

unread,
Jul 27, 2002, 7:26:06 PM7/27/02
to
I know a print statement cannot stay in a lambda function, however as a
newbie I ask : why ?

Michele

Erik Max Francis

unread,
Jul 27, 2002, 7:31:09 PM7/27/02
to
Michele Simionato wrote:

Because a lambda is an expression, not a statement.

--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ See the son in your bad day / Smell the flowers in the valley
\__/ Chante Moore
Bosskey.net: Aliens vs. Predator 2 / http://www.bosskey.net/avp2/
A personal guide to Aliens vs. Predator 2.

Gerald Squelart

unread,
Jul 28, 2002, 1:50:01 AM7/28/02
to
"Erik Max Francis" <m...@alcyone.com> wrote

> Michele Simionato wrote:
> > I know a print statement cannot stay in a lambda function, however as
> > a newbie I ask : why ?
> Because a lambda is an expression, not a statement.
Therefore, a lambda *expects* an expression, not a statement.

However, you could indirectly include a print statement in the course of a running
lambda expression:
def printArg(arg):
print arg
return arg
l = lambda x: printArg(x)
a = l(10) # will print 10 and assign 10 to a
map(l, range(5)) # will print numbers 0 to 4 and return [0, 1, 2, 3, 4]
It may be useful to debug a lamdba expression.

Cheers,
Gerald.


Daniel Fackrell

unread,
Jul 28, 2002, 1:59:50 AM7/28/02
to

Correct me if I'm wrong, but doesn't this just create an anonymous
function that calls the named function printArg? Besides the added
function-call overhead, how are the two following lines functionally
different?

l = lambda x: printArg(x)

l = printArg

Daniel Fackrell

Bryan Olson

unread,
Jul 28, 2002, 2:33:47 AM7/28/02
to
Alex Martelli wrote:
> Steve Holden wrote:
Alex Martelli had written:

>>>The poster is typically nonplusses that all buttons print 'fum'.
>>>
>>
>>I would be nonplussed if that code even *compiled*, given that "print" is
>>a keyword and lambda takes an expression not a statement.
>
>
> Right - you caught my little trap. I don't regret using it, though,
> because it DID catch a couple of lambda-lovers...

First, who do you think you're kidding? It was your mistake not
your trap. Second, this question is better answered by people who
actually understand use of lambda.

[...]


> I think the reason why Guido suggests it's a wart is that it IS a wart.
>
> Sure, backwards compatibility mandates lambda stay, but I think it's
> worth emphasizing that it's there ONLY for backwards compatibility,
> and using def is better.

The mistake was limiting lambda to expressions.


--Bryan

Bryan Olson

unread,
Jul 28, 2002, 2:45:22 AM7/28/02
to
Paul Rubin wrote:

> There's a middle ground that says the name "lambda" (which comes from
> Lisp) wasn't a good choice and another name should have been used
> instead, like maybe 'func', which does the same thing. I guess that's
> reasonable. I'm used to lambda from Lisp but another name would
> probably be less scary to non-Lisp-users.

I agree, though the name "lambda" actually pre-dates Lisp. It comes
from Alonzo Church's "lambda Calculous" of the 1930's.

ML uses "fn", which like "func" reads beautifully. The construct ceases
to be arcane when people hear that "lambda x: x * 2 + 3" reads as "that
function which applied to x, returns x * 2 + 3".


--Bryan

Gerald Squelart

unread,
Jul 28, 2002, 2:58:29 AM7/28/02
to
"Daniel Fackrell" <unle...@learn2think.org> wrote

Yeah, that was a very simple expression, to show how it could work... Of course this
lambda function is pretty lame!

Well, my point was: if you have a lambda function used like this:
map(lambda x: big_expression, some_list)
and now you want to print something from the anonymous function, then it's possible
by just adding the stoopid printArg() function around some subexpression, without
having to remove the complete lambda expression and replacing it by a function def
and a call...
You choose:
def lambdaReplacement(x):
print stuff
return big_expression
map(lambdaReplacement, some_list)
- or -
def printArg(x):
print x
return x
map(lambda x: expression_with_printArg, some_list)

And it's easier to remove later, if needed, methinks

Of course, some think lambda is inherently evil, I can't argue with that, it's a
matter of taste...
Let's not start this war please ;-)

G.


Bryan Olson

unread,
Jul 28, 2002, 3:49:23 AM7/28/02
to
Paul Rubin wrote:

> I don't see why the anti-lambda contingent doesn't want to also
> get rid of anonymous scalar expressions. I mean,
>

> a = b + (c * d)

I don't think that's really a best example. Functions and procedures
are supposed to be fist-class in Python. We don't have to name lists,
tuples, or dictionaries, so why should we have to name procedures and
classes? Python is supposed to be regular.

The inability to define procedures independently of their names is a
terrible wart. It deceives people. The requirement to "def" a
procedure to a name hides the fact that the procedure is truly a value,
and no more limited to standing by a name than is an integer. Yes, it
is often (usually) useful to assign that value to one or more names; the
same may be said of lists and dictionaries.


I remember the time when I thought of lambda as weird, or "arcane". I
was learning Lisp, and I had already studied the fundamentals of Basic,
Pascal, FORTRAN and C. Now I see that the reason I found the lambda
difficult was because I was only familiar with languages in which
procedures are not first-class. (Well, admittedly also because the
traditional term "lambda" didn't ring like other reserved words). In
those other language, the name bound to an address to which the compiler
would put a jump. Anonymous function were important to my understanding
of functions as values, and breaking of my FORTRAN-think.

We certainly don't want to re-enforce the false notion that functions
and procedures are special things with intrinsic names. They may be
stored in a list as naturally as assigned to a name. And yet "def
a[3](x): ..." doesn't parse.

Expand lambda, maybe rename it. But do not eliminate it, because
anonymous functions and functions-as-values go hand-in-hand.


--Bryan

Fredrik Lundh

unread,
Jul 28, 2002, 3:58:37 AM7/28/02
to
Bryan Olson wrote:

> The mistake was limiting lambda to expressions.

Guido can channel himself (or Tim will do it), but from what
I can tell, he's always said that the "mistake" was adding
something to the language that almost, but not completely,
works like lambdas do in other languages.

(lambda, map, filter, etc was contributed code)

the really big usage problem (whether you knew lambdas
from other languages or not) used to be that they were a
real pain to use under the LGB scoping rule. with the intro-
duction of nested scopes, that problem no longer exists.

to fix the other "mistake", some needs to come up with a
really great syntax (and get michael hudson to implement
it for them ;-). ideas are welcome.

</F>


John Roth

unread,
Jul 28, 2002, 7:49:58 AM7/28/02
to

"Fredrik Lundh" <fre...@pythonware.com> wrote in message
news:NuN09.1347$HY3.3...@newsc.telia.net...

What's the problem with that? If we give up the notion
that anonamous functions need to look like expressions,
it should be simple. Just stick the function definition inline,
indentation and all. The only issue is defining a new keyword,
since lambda doesn't work that way. "def" would probably
work, since it's only allowed at statement level now.

John Roth
>
> </F>
>
>


Michele Simionato

unread,
Jul 28, 2002, 10:52:42 AM7/28/02
to
Now I see the source of my confusion. I thought the print "statement"
was
actually an expression with result None. However in Python

result=print("something")

gives a syntax error. Then my question is: why Guido decided to keep
the distinction between statements (with no value returned) and
expressions ? what are the advantages ? is it a matter of personal
taste ? Sorry if these
questions sounds naive,

Michele

Yigal Duppen

unread,
Jul 28, 2002, 12:03:05 PM7/28/02
to
> So I know what lambda functions are, they're syntax and how they're used.

> However I'm not sure *why* one would use a lambda function. What's the
> advantage that they offer over a regular function?

Back in the old days, before 2.2 came out with its list comprehensions, they
had their use.

I am a big fan of constructs like map, filter and reduce; by using one
function, they allow you to eliminate looping constructs from your code,
keeping it shorter and (usually) clearer.


However, if you have a list of objects:
>>> class A:
... def value(self):
... return "x"
>>> list_of_as = [A(), A(), A()]

and you want to extract the values using map(), you needed to do:
>>> map(lambda x: x.value(), list_of_as)
['x', 'x', 'x']

Luckily, list comprehensions remove that need
>>> [x.value() for x in list_of_as]
['x', 'x', 'x']

Since I started to use list comprehensions, I haven't needed a single
lambda.

YDD
--
.sigmentation fault

Andrae Muys

unread,
Jul 28, 2002, 8:47:56 PM7/28/02
to
Carl Banks <imb...@vt.edu> wrote in message news:<ahsmda$pjm$2...@solaris.cc.vt.edu>...

> Second, if you're going to do it right often, you might want to wrap
> it up in a function like this:
>
> def sort_the_right_way (f, a):
> aux = [ (f(x), x) for x in a ]
> aux.sort()
> a[:] = [ x for __, x in aux ]
>
> In which case, the temptation to use lambda returns:
>
> sort_the_right_way (lambda x:x[1], a)

Indeed. I personally only find lambda helpful when I require a truely
trivial function, swapping the order of a pair: lambda (x,y):(y,x);
applying the second argument: lambda x,f:f(x); etc.

Andrae Muys

Bo M. Maryniuck

unread,
Jul 29, 2002, 3:49:46 AM7/29/02
to
On Saturday 27 July 2002 22:17, Fredrik Lundh wrote:
> Oh, sorry, I didn't mean you. I meant the "lambda lovers have
> childhood traumas" guy. If he cannot defend his position with-
> out stuff like that, it must be a pretty worthless position.

Ouuhhh! Maybe ESR is "bad programmer",
since he loves lambdas in Python... :D

--
Sincerely yours, Bogdan M. Maryniuck

"Linux poses a real challenge for those with a taste for late-night
hacking (and/or conversations with God)."
(By Matt Welsh)


Tim Peters

unread,
Jul 29, 2002, 5:26:17 AM7/29/02
to
[Fredrik Lundh]

> Guido can channel himself (or Tim will do it), but from what
> I can tell, he's always said that the "mistake" was adding
> something to the language that almost, but not completely,
> works like lambdas do in other languages.

I don't think so -- Guido isn't a fan of functional programming styles, and
plain doesn't like lambda. Except, of course, when he uses it, which is
always for trivial little function arguments, in accord with his
oft-repeated claim that the functional gimmicks were never intended to be
more than "minor conveniences" (which he later amended to "minor
annoyances", after people started clamoring for more of the same). It's not
that they don't work exactly the same way in Python as some people expect
them to, it's more that programming styles based on composition of
higher-order functions simply aren't in his vision of what programming in
Python should be.

> (lambda, map, filter, etc was contributed code)

Change "etc" to "and reduce" and you've got the whole set. Those four were
contributed by the same person, in one gulp. I don't think Guido has tried
it, but he'd like Haskell much more than he'd like Scheme; e.g., listcomps
"felt right" to him, while non-trivial maps and filters don't, and never
will.

> the really big usage problem (whether you knew lambdas
> from other languages or not) used to be that they were a
> real pain to use under the LGB scoping rule. with the intro-
> duction of nested scopes, that problem no longer exists.

Guido's not much of a fan of nested scopes, either, although I believe I've
channeled evidence of minor flip-flopping on that. Indeed, by and large
people seemed quite happy with the LGB rules *until* lambda got introduced.
Then "scope whining" started for real. I expect he'll stay happy enough
with lexical scoping until people start writing inscrutably nested
monstrosities with it. Objects are Python's intended way to carry state,
and Guido isn't a Paradigm-Neutral language designer (you know where to go
if you want one of those).

> to fix the other "mistake", some needs to come up with a
> really great syntax (and get michael hudson to implement
> it for them ;-). ideas are welcome.

Well, I can channel that one: not bloody likely. If Guido's time machine
wasn't in the shop for million-year warranty service, I expect Python
wouldn't have any spelling of anonymous functions today. Note that toward
the tail end of Guido's OSCON 2002 "State of the Python Union" keynote
address:

http://www.python.org/doc/essays/ppt/ [bottom link on the page]

two language features are mentioned as being "failed experiments" that only
compatibility prevents throwing away:

`back ticks`
lambda

With subtle clues like that, channeling is easier than it looks <wink>.


JB

unread,
Jul 29, 2002, 10:50:07 AM7/29/02
to
Tim Peters wrote:

> [...]


> two language features are mentioned as being "failed
> experiments" that only compatibility prevents throwing
> away:
>
> `back ticks`
> lambda

(1) Why are back ticks a failure? I love them.
(2) I just wanted to submit a PEP in which I should have
proposed to switch to prefix notation like CL. To
judge from what you wrote, Mr Guido would not love
this proposal too much either?

--
JB


-----------== Posted via Newsfeed.Com - Uncensored Usenet News ==----------
http://www.newsfeed.com The #1 Newsgroup Service in the World!
-----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =-----

Steve Holden

unread,
Jul 29, 2002, 11:05:52 AM7/29/02
to
"John Roth" <john...@ameritech.net> wrote ...
> "Fredrik Lundh" <fre...@pythonware.com> wrote...
I'd like to see an example of this, since it appears you haven't fully
thought this through. You mean you'd like to be able to write some thing
like the following:

for word in 'fee fie fo fum'.split():
Button(frame, command=lambda:
print word)

This is currently acceptable in Python because the lambda's inside a
parenthesised argument list. How would I add a second line to the lambda?
I'm always suspicious of phrasing like "all you need to do..." or "the only
issue...", since it often indicates that insufficient thought has gone into
a proposal. And the reason I'm suspicious when other people do it is because
I've watched me doing it enough to get into trouble!

Conclusion: this idea is currently 0.345-baked :-)

regards
-----------------------------------------------------------------------
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------

Steve Holden

unread,
Jul 29, 2002, 11:10:11 AM7/29/02
to
"Michele Simionato" <mi...@pitt.edu> wrote in message
news:2259b0e2.02072...@posting.google.com...

He made that decision for the same reason he decided not to allow
assignments inside expressions. You can find the justification in the FAQ if
you look for it ... 6.30: Why can't I use assignment in an expression.

Steve Holden

unread,
Jul 29, 2002, 11:15:01 AM7/29/02
to
"Carl Banks" <imb...@vt.edu> wrote in message
news:ahuqd8$1a7$1...@solaris.cc.vt.edu...
[ ... ]

>
> Personally, I don't care about saving lines, per se. For me, lambda
> helps me to avoid stopping mid-function call, scrolling many or few
> lines to implement the function as a def, and returning. I.e.,
> lambdas save me cursor movement.
>
Well your programming style and mine are very different. I thought the whole
point of using functions was to provide a usable abstraction of a portion of
a program's logic. I therefore *conceptualize* a function long before I
write it, and don't feel the need to make it's source code explicit just
because I've caslled it somewhere in my (developing) program.

it-take-all-sorts-to-make-a-newsgroup-ly y'rs - steve

Fredrik Lundh

unread,
Jul 29, 2002, 11:51:08 AM7/29/02
to
Tim Peters wrote:

> I don't think so -- Guido isn't a fan of functional programming styles, and
> plain doesn't like lambda. Except, of course, when he uses it, which is
> always for trivial little function arguments, in accord with his
> oft-repeated claim that the functional gimmicks were never intended to be
> more than "minor conveniences" (which he later amended to "minor
> annoyances", after people started clamoring for more of the same). It's not
> that they don't work exactly the same way in Python as some people expect
> them to

my memories of who said what and when is starting to get mixed
up, but I'm pretty sure I've seen and heard comments along those
lines over the years, including this c.l.py comment from 1996:

Opinions on ugliness can vary, but personally, I just wish I'd never
given in to the pressure to add lambda in the first place. Nested
functions are somewhat of an oddity, but once you say "lambda" you
recall a whole complex of semantics for those who are used to it.

but I might be wrong.

> it's more that programming styles based on composition of higher-order functions
> simply aren't in his vision of what programming in Python should be.

that's true. but that doesn't explain why did we added nested scopes
to 2.1? did you guys just fail to stop Jeremy from checking them in, or
what happened?

> > to fix the other "mistake", some needs to come up with a
> > really great syntax (and get michael hudson to implement
> > it for them ;-). ideas are welcome.

(I think that should have been "greg ewing needs to come up
with a really great syntax, and get michael hudson to implement
it"... or maybe we could revive the old "frowning guido" design?)

> Well, I can channel that one: not bloody likely.

oh, I don't know about that. I definitely remember that the BDFL was
rather positive to the idea when we discussed this back at SPAM8 (or
whenever it was). iirc, Eric Raymond volunteered to come up with a
"smalltalk block"-like design and a patch. hasn't happened yet...

</F>


Aahz

unread,
Jul 29, 2002, 12:00:13 PM7/29/02
to
In article <3d455...@news.newsgroups.com>, JB <j...@hotmail.com> wrote:

>Tim Peters wrote:
>>
>> two language features are mentioned as being "failed
>> experiments" that only compatibility prevents throwing
>> away:
>>
>> `back ticks`
>> lambda
>
>(1) Why are back ticks a failure? I love them.

If you're using backticks frequently, you're probably not programming
Pythonically. There's already repr() to produce the same result as
backticks, and backticks have the problem that in many fonts they're
nearly indistinguishable from single quotes.
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/

Michael Hudson

unread,
Jul 29, 2002, 12:10:59 PM7/29/02
to
"Fredrik Lundh" <fre...@pythonware.com> writes:

> to fix the other "mistake", some needs to come up with a
> really great syntax (and get michael hudson to implement
> it for them ;-). ideas are welcome.

I only implement syntax for things I think are a good idea :)

I have no problem coming up with names for functions...

Cheers,
M.

--
If i don't understand lisp, it would be wise to not bray about
how lisp is stupid or otherwise criticize, because my stupidity
would be archived and open for all in the know to see.
-- Xah, comp.lang.lisp

JB

unread,
Jul 29, 2002, 12:48:44 PM7/29/02
to
Aahz wrote:

> In article <3d455...@news.newsgroups.com>, JB
> <j...@hotmail.com> wrote:
>>Tim Peters wrote:
>>>
>>> two language features are mentioned as being "failed
>>> experiments" that only compatibility prevents throwing
>>> away:
>>>
>>> `back ticks`
>>> lambda
>>
>>(1) Why are back ticks a failure? I love them.
>
> If you're using backticks frequently, you're probably not
> programming
> Pythonically. There's already repr() to produce the same
> result as backticks, and backticks have the problem that
> in many fonts they're nearly indistinguishable from single
> quotes.

I do not understand this. I use __repr__ *and* backticks.
For example

class AnyClass:
defr __repr__(self):
...

a = AnyClass()
myfile.write(`a`)

I use this construction rather frequently. What is wrong
with it?

Daniel Fackrell

unread,
Jul 29, 2002, 1:03:02 PM7/29/02
to
"JB" <j...@hotmail.com> wrote in message
news:3d457...@news.newsgroups.com...


repr() != __repr__()

`object` == repr(object), both of which will call object.__repr__, if it
exists.

I think that the general consensus is that repr(object) is much more
readable than the relatively obscure syntax `object`. Also, as written
previously, the ` is easily confused with ' in many fonts.

--
Daniel Fackrell (unle...@learn2think.org)
When we attempt the impossible, we can experience true growth.


Donn Cave

unread,
Jul 29, 2002, 1:19:48 PM7/29/02
to
Quoth JB <j...@hotmail.com>:

What he said - "... nearly indistinguishable from single quotes."
Density at the expense of legibility is why I'd say it doesn't really
fit with my ideal of Python programming style.

On the other hand, list comprehensions certainly would fall in that
category too, and there's no question that I'm out of touch with the
prevailing sentiment on comp.lang.python about things like this.
And the distribution library appears to use `` rather liberally -
probably more than repr(). Obviously this doesn't make it any
better (is Perl more wonderful for all the people who use it, or
Visual Basic, C++, etc?) But we can't pretend there's a consensus.

Donn Cave, do...@u.washington.edu

Michele Simionato

unread,
Jul 29, 2002, 2:14:01 PM7/29/02
to
It seems Guido took his time machine to answer my question four days ago
at OSCON. From http://www.python.org/doc/essays/ppt/ , Python Regrets:

"print should've been a function"


Michele

John Roth

unread,
Jul 29, 2002, 2:43:11 PM7/29/02
to

"Steve Holden" <sho...@holdenweb.com> wrote in message
news:7Rc19.92310$724....@atlpnn01.usenetserver.com...

> "John Roth" <john...@ameritech.net> wrote ...
> > "Fredrik Lundh" <fre...@pythonware.com> wrote...
> >

Button(frame, command = def ():
print word
)

This isn't really the world's best example, because IMO, the
lambda form is easier to read for something this small. However,
it does give the guts of the idea:

1. instead of lambda (which needs to stay as is for backward
compatibility) it uses 'def' as the keyword.

2. The remainder of the syntax exactly models def, including
statement indentation within the expression. Notice that the
first statement in the anonamous function has to be indented
two from the preceeding line, because the continuation of
the expression has to still be indented from the line with the
'def', and dedented from the statements.

3. The use of 'def' here reflects a comment from one of
the posters that it's easy for people without experience in
languages with first class functions to miss the fact that Python
has them.

Hope this helps. I considered it simple enough that it really
didn't need an example.

John Roth

Aahz

unread,
Jul 29, 2002, 3:31:13 PM7/29/02
to
In article <3d457...@news.newsgroups.com>, JB <j...@hotmail.com> wrote:

>Aahz wrote:
>>
>> If you're using backticks frequently, you're probably not programming
>> Pythonically. There's already repr() to produce the same result as
>> backticks, and backticks have the problem that in many fonts they're
>> nearly indistinguishable from single quotes.
>
>I do not understand this. I use __repr__ *and* backticks.
>For example
>
>class AnyClass:
> defr __repr__(self):
> ...
>
>a = AnyClass()
>myfile.write(`a`)

You should use

myfile.write(repr(a))

It's much clearer that you're *NOT* doing

myfile.write('a')

Yes, the Python std lib has backticks in it. Cleaning that up would
likely be the first step toward deprecating backticks. In any event,
backticks will certainly be available at least until Python 3.0.

Sean 'Shaleh' Perry

unread,
Jul 29, 2002, 4:03:42 PM7/29/02
to
>
> Yes, the Python std lib has backticks in it. Cleaning that up would
> likely be the first step toward deprecating backticks. In any event,
> backticks will certainly be available at least until Python 3.0.

well seeing as the python group went through and replaced all of the string
exceptions with class based ones why not have another pass at modernizing
python's lib?

I am not suggesting we kill lambda/map with list comps but little things like
backticks can be killed fairly quickly.

I could submit a patch for the repr cleanup in pretty short order.

Huaiyu Zhu

unread,
Jul 29, 2002, 3:53:07 PM7/29/02
to
Fredrik Lundh <fre...@pythonware.com> wrote:
>to fix the other "mistake", some needs to come up with a
>really great syntax (and get michael hudson to implement
>it for them ;-). ideas are welcome.

No great syntax here, but some ideas on why it is difficult syntax-wise (in
the hope that someone can overcome them).

Python uses indentation to denote lexical scope at or above the statement
level, while using parenthesis at the expression level. It is rather easy
to embed parenthesis inside indentation, but the other way is difficult.

So to allow statements in lambdas, it is either necessary to delimit
statements with some begin/end marker in lieu of indentation, or to come up
with a way to embed indentation scoping inside parenthesis scoping.

Another possibility is to allow only those statements that do not have
further scopes. For example, print and assert would be allowed but
if/then/else would not.

Huaiyu

JB

unread,
Jul 29, 2002, 4:56:18 PM7/29/02
to
Daniel Fackrell wrote:

> `object` == repr(object), both of which will call
> object.__repr__, if it exists.
>
> I think that the general consensus is that repr(object) is
> much more
> readable than the relatively obscure syntax `object`.
> Also, as written previously, the ` is easily confused with
> ' in many fonts.

Maybe. But using the backticks is much shorter, much more
elegant. I should not want to do without them.
Readability or even legibility has never been a problem for
me. (I have problem with booleans, but this is another
story.)

Sean 'Shaleh' Perry

unread,
Jul 29, 2002, 5:00:20 PM7/29/02
to

On 29-Jul-2002 Neil Schemenauer wrote:

> Sean 'Shaleh' Perry wrote:
>> I could submit a patch for the repr cleanup in pretty short order.
>
> Guido's not big on this kind of "hit and run" cleanup. He prefers it if
> someone looks at the entire module while modernizing it. Keep in mind
> though, I'm an amateur when it coming to channelling the BDFL and he
> might tell you differently himself.
>
> Neil

That is a reasonable attitude.

Comments from the direct python hackers? Would more work on the lib be
welcomed? Do we want the standard library to be a good example of python best
practices? (sorry i know that sounds like a loaded question).

Neil Schemenauer

unread,
Jul 29, 2002, 4:55:46 PM7/29/02
to

Donn Cave

unread,
Jul 29, 2002, 6:01:39 PM7/29/02
to
Quoth "Sean 'Shaleh' Perry" <shale...@attbi.com>:

| On 29-Jul-2002 Neil Schemenauer wrote:
|> Sean 'Shaleh' Perry wrote:
|>| I could submit a patch for the repr cleanup in pretty short order.
|>
|> Guido's not big on this kind of "hit and run" cleanup. He prefers it if
|> someone looks at the entire module while modernizing it. Keep in mind
|> though, I'm an amateur when it coming to channelling the BDFL and he
|> might tell you differently himself.
|
| That is a reasonable attitude.
|
| Comments from the direct python hackers? Would more work on the lib be
| welcomed? Do we want the standard library to be a good example of python best
| practices? (sorry i know that sounds like a loaded question).

I would be opposed, personally. (Since I don't know what "direct
python hacker" means, I'm probably not one, but will comment anyway
since it seems to me I brought it up in the first place.)

1. It's up to the people who write the code. There are probably
some standards for contributed code, I hope so anyway, but I
wouldn't want to expect someone to maintain a module that had
been recoded at a later date for essentially religious reasons.

2. The distribution library is a useful reality check in cases like
this. Want to know how people really use repr, str, lambda, integer
arithmetic, you name it? The distribution library represents a
group of reasonably accomplished programmers, whose work we all use.
They don't always follow the party line on everything, but past
any initial submission requirements, they're entitled to call their
own shots on usage, and I think that's actually useful. It helps
us to distinguish between comp.lang.python dogma and what everyone's
really doing.

If they want to ask me how to code their programs, I'd sure advise
them to get rid of the back ticks and I wouldn't take any BS about
how elegant and readable they are. But I want them to see that on
their own, I don't want to whitewash their code so we can pretend
everyone agrees about these matters.

Donn Cave, do...@u.washington.edu

Tim Peters

unread,
Jul 29, 2002, 5:50:10 PM7/29/02
to
[Neil Schemenauer]

> Guido's not big on this kind of "hit and run" cleanup. He prefers it if
> someone looks at the entire module while modernizing it. Keep in mind
> though, I'm an amateur when it coming to channelling the BDFL and he
> might tell you differently himself.

[Sean 'Shaleh' Perry]


> That is a reasonable attitude.
>
> Comments from the direct python hackers? Would more work on the lib be
> welcomed? Do we want the standard library to be a good example
> of python best practices? (sorry i know that sounds like a loaded
> question).

Best practice is, as Neil said, to *think* about a module, and hard, when
"cleaning it up". Widespread mechanical edits aren't welcome, and
especially since the last such effort (massive conversion to string methods)
introduced several bugs in the process. Better to find modules to love
long-term and keep them deeply beautiful, than to splash paint on boils at
random just to cover up the oozing pus <gross wink>.


Gerald Squelart

unread,
Jul 29, 2002, 8:34:49 PM7/29/02
to
"Steve Holden" <sho...@holdenweb.com> wrote
> "Michele Simionato" <mi...@pitt.edu> wrote

> > why Guido decided to keep
> > the distinction between statements (with no value returned) and
> > expressions ? what are the advantages ? is it a matter of personal
> > taste ?
> He made that decision for the same reason he decided not to allow
> assignments inside expressions. You can find the justification in the FAQ if
> you look for it ... 6.30: Why can't I use assignment in an expression.

Static FAQ is there: http://www.python.org/doc/FAQ.html
6.30 is there: http://www.python.org/doc/FAQ.html#6.30

However, as you point out, 6.30 is 'Why can't I use an assignment in an
expression?', whereas the question asked here is 'Why is there a distinction between
statements and expressions?'.
You write 'He made that decision for the same reason...'; how do you know this? I
had a quick look, but didn't see anything about the question asked by Michele. It
may be a good thing to add to the FAQ...

Cheers,
Gerald.


Sean 'Shaleh' Perry

unread,
Jul 29, 2002, 8:44:55 PM7/29/02
to
>
> Best practice is, as Neil said, to *think* about a module, and hard, when
> "cleaning it up". Widespread mechanical edits aren't welcome, and
> especially since the last such effort (massive conversion to string methods)
> introduced several bugs in the process. Better to find modules to love
> long-term and keep them deeply beautiful, than to splash paint on boils at
> random just to cover up the oozing pus <gross wink>.
>

lovely image there ......

is there a place which documents modules needing a steward?

Michael Gilfix

unread,
Jul 29, 2002, 9:09:21 PM7/29/02
to
I second that. Or even more interestingly, is there a place which
lists who has ownership of each module?

-- Mike

On Mon, Jul 29 @ 17:44, Sean 'Shaleh' Perry wrote:
> lovely image there ......
>
> is there a place which documents modules needing a steward?
>

> --
> http://mail.python.org/mailman/listinfo/python-list
`-> (shalehperry)

--
Michael Gilfix
mgi...@eecs.tufts.edu

For my gpg public key:
http://www.eecs.tufts.edu/~mgilfix/contact.html

Donn Cave

unread,
Jul 30, 2002, 1:26:50 AM7/30/02
to
Quoth "Steve Holden" <sho...@holdenweb.com>:

| "Carl Banks" <imb...@vt.edu> wrote in message
| news:ahuqd8$1a7$1...@solaris.cc.vt.edu...
| [ ... ]
|> Personally, I don't care about saving lines, per se. For me, lambda
|> helps me to avoid stopping mid-function call, scrolling many or few
|> lines to implement the function as a def, and returning. I.e.,
|> lambdas save me cursor movement.
|
| Well your programming style and mine are very different. I thought the whole
| point of using functions was to provide a usable abstraction of a portion of
| a program's logic. I therefore *conceptualize* a function long before I
| write it, and don't feel the need to make it's source code explicit just
| because I've caslled it somewhere in my (developing) program.

Perhaps that is indeed the point - abstraction, and control of
abstraction. I think you will agree that your choice of abstraction
is a key question in your whole program design, not something where
you'd just take all you get, willy-nilly. Where you want abstraction,
functions are indeed useful. Where you do not, but you still need a
function, you have lambda.

These would often be functions that are so trivial that they can
more economically simply stand for themselves. But in any case,
you can ask "what do I get out of abstracting this", and the answer
may just be "nothing".

Donn Cave, do...@drizzle.com

Michael Hudson

unread,
Jul 30, 2002, 4:55:04 AM7/30/02
to
"Donn Cave" <do...@u.washington.edu> writes:

> What he said - "... nearly indistinguishable from single quotes."
> Density at the expense of legibility is why I'd say it doesn't really
> fit with my ideal of Python programming style.

On one of Guido's slides he also mentions problems with typesetters
changing both `a` and 'a' to `a'....

> On the other hand, list comprehensions certainly would fall in that
> category too, and there's no question that I'm out of touch with the
> prevailing sentiment on comp.lang.python about things like this.

Hey, I like <>.

> And the distribution library appears to use `` rather liberally -
> probably more than repr().

Maybe they're older? Not sure on this one -- both are certainly
pretty old.

> Obviously this doesn't make it any better (is Perl more wonderful
> for all the people who use it, or Visual Basic, C++, etc?) But we
> can't pretend there's a consensus.

Good sigmonster :)

Cheers,
M.

--
Roll on a game of competetive offence-taking.
-- Dan Sheppard, ucam.chat

Michael Hudson

unread,
Jul 30, 2002, 5:21:35 AM7/30/02
to
Neil Schemenauer <n...@python.ca> writes:

> Sean 'Shaleh' Perry wrote:
> > I could submit a patch for the repr cleanup in pretty short order.
>
> Guido's not big on this kind of "hit and run" cleanup.

It scares the crap out of *me* when people do this. Don't know what
it does to Guido.

> He prefers it if someone looks at the entire module while
> modernizing it.

I think a good strategy is: if you are working on a module *anyway*
(adding new functionality, fixing bugs, whatever) then it's reasonable
to modernize the style while you're at it (though it's sensible to do
the style changes and the code changes in different checkins). The
theory being that if you're working on a module, you hope you
understand what you're changing...

Cheers,
M.

--
I never disputed the Perl hacking skill of the Slashdot creators.
My objections are to the editors' taste, the site's ugly visual
design, and the Slashdot community's raging stupidity.
-- http://www.cs.washington.edu/homes/klee/misc/slashdot.html#faq

Michael Hudson

unread,
Jul 30, 2002, 5:23:51 AM7/30/02
to
Michael Gilfix <mgi...@eecs.tufts.edu> writes:

> On Mon, Jul 29 @ 17:44, Sean 'Shaleh' Perry wrote:
> > is there a place which documents modules needing a steward?

Don't think so. The distutils are always looking for some love...

> I second that. Or even more interestingly, is there a place which
> lists who has ownership of each module?

Don't think there's one of them either. Most modules aren't really
"owned", there's just someone who does most of the looking after. cvs
logs are the best way of finding this out.

Cheers,
M.

--
This is an off-the-top-of-the-head-and-not-quite-sober suggestion,
so is probably technically laughable. I'll see how embarassed I
feel tomorrow morning. -- Patrick Gosling, ucam.comp.misc

Andreas Kostyrka

unread,
Jul 30, 2002, 5:34:13 AM7/30/02
to
Am Sam, 2002-07-27 um 09.11 schrieb Alex Martelli:
> The lambda solution doesn't work. At all. It gives you a SyntaxError
> if you try it!
Well, I usually type sys.stdout.write in a lambda without even thinking
to much :)
>
> lambda cannot include a statement. print is a statement. Oooops...!-)
>
> So, if you structure your code with lambda, the moment you want
> to add a print statement, boom -- can't do. You have to restructure
Why would I want to add a print statement for debugging. (Admittingly
I've done this before, but these days are long gone)
With python it's trivial to define an automatic instrumentation with the
tracing support. Actually, print statements are used usually by people
to lazy to do it right. Usually, when you get to your first hard problem
in a small piece of old code (say 25kloc, deployment started in 1996,
and development never stopped) where you need much instrumentation to
get a feel how certain things are done. (Well the app contains at least
3 seperate layers of db abstraction layers, each one on top of the older
one ;) )

> your code to use def instead. When you remove the print after it's
> done its debugging-help job, will you restructure once again to
> take the def away in favor of lambda... and again NEXT time you
> need to have a statement there too, etc, etc...? What a lot of
> purposeless code churning...!
Again, why would I do that?
lambda x: x
->
lambda x: (x,sys.stdout.write("x=%d\n" % x))[0])

> Use def and avoid all of this silly self-imposed useless work.
Use the best tool for the task. lambda are quite nice for small wrapper
functions that rearrange arguments.
Basically, lambda can sometimes substitute for the code block objects
(like in smalltalk).
So IMHO, there is nothing wrong with lambda. Just don't use a fork to
eat soup. At least do not complain about the experience to c.l.p ;)

Andreas


John Roth

unread,
Jul 30, 2002, 7:29:25 AM7/30/02
to

"Huaiyu Zhu" <hua...@gauss.almadan.ibm.com> wrote in message
news:slrnakb792...@gauss.almadan.ibm.com...

> Fredrik Lundh <fre...@pythonware.com> wrote:
> >to fix the other "mistake", some needs to come up with a
> >really great syntax (and get michael hudson to implement
> >it for them ;-). ideas are welcome.
>
> No great syntax here, but some ideas on why it is difficult
syntax-wise (in
> the hope that someone can overcome them).
>
> Python uses indentation to denote lexical scope at or above the
statement
> level, while using parenthesis at the expression level. It is rather
easy
> to embed parenthesis inside indentation, but the other way is
difficult.
>
> So to allow statements in lambdas, it is either necessary to delimit
> statements with some begin/end marker in lieu of indentation, or to
come up
> with a way to embed indentation scoping inside parenthesis scoping.

Exactly. AFIK, everyone has been pursuing the first path,
while it is conceptually simple to do the second. See my response to
Steve Holden's comment for how it would look in practice.
It's easy to write, not quite so easy to look at. I have no idea whether
it would be easy to implement in the compiler. (The interpreter
shouldn't
care.)

The trick is to use 'def' as the keyword, not 'lambda.'

>
> Another possibility is to allow only those statements that do not have
> further scopes. For example, print and assert would be allowed but
> if/then/else would not.

Why bother with the restrictions? Fredrik had the right idea when
he said that we needed something to make it obvious that functions
are first class objects. That is, allow anonamous functions anywhere
you can have a function object.

John Roth
>
> Huaiyu


Jonathan Hogg

unread,
Jul 30, 2002, 8:21:56 AM7/30/02
to
On 30/7/2002 12:29, in article ukcu02s...@news.supernews.com, "John
Roth" <john...@ameritech.net> wrote:

> Why bother with the restrictions? Fredrik had the right idea when
> he said that we needed something to make it obvious that functions
> are first class objects. That is, allow anonamous functions anywhere
> you can have a function object.

How far does one go? Classes are first-class objects, should we also have
anonymous classes?

>>> foo = (class:
... def __init__( self, x y ):
... self.x = x
... self.y = y
... )( 5, 6 )
>>>
>>> foo.x
5
>>>

I'm a fan of lambda, but when a function is complex enough that it can't be
done in an in-(one-)line lambda then it should be pulled out and given a
name.

Jonathan

Daniel Fackrell

unread,
Jul 30, 2002, 9:36:09 AM7/30/02
to
"John Roth" <john...@ameritech.net> wrote in message
news:ukb31el...@news.supernews.com...

<snip>

> for word in 'fee fie fo fum'.split():
> Button(frame, command = def ():
> print word
> )
>
> This isn't really the world's best example, because IMO, the
> lambda form is easier to read for something this small. However,
> it does give the guts of the idea:

<snip>

> 2. The remainder of the syntax exactly models def, including
> statement indentation within the expression. Notice that the
> first statement in the anonamous function has to be indented
> two from the preceeding line, because the continuation of
> the expression has to still be indented from the line with the
> 'def', and dedented from the statements.

IIRC, there's no such ting as "indenting two" in Python as the size of an
indentation is automatically detected as you go along, making the following
indentation style valid (although no one would ever want to do it):

toplevel
secondlevel
thirdlevel
secondlevel
thirdlevel
fourthlevel
secondlevel
toplevel

John Roth

unread,
Jul 30, 2002, 11:59:44 AM7/30/02
to

"Daniel Fackrell" <unle...@DELETETHIS.learn2think.org> wrote in
message news:3d46964b$1...@hpb10302.boi.hp.com...

The reason I say "indenting 2" is that you need two
dedents to make it work: one to close the def, which does
not have it's own indent, and one to finish off the expression
in which the def is imbedded.

Does this make it clearer?

John Roth

John Roth

unread,
Jul 30, 2002, 12:05:43 PM7/30/02
to

"Jonathan Hogg" <jona...@onegoodidea.com> wrote in message
news:B96C4374.ECA5%jona...@onegoodidea.com...

I tend to agree with you on that one, but it's a matter of style. I
observe
that e.g. Smalltalk style does anonymous code blocks all over the place.

As far as anonamous classes, again, it's a matter of style. I wouldn't
do that
simply because I think it complicates the code too much. On the other
hand, people who regularly program in languages that let that happen
might have examples where it makes sense.

There's no reason my proposal couldn't be extended to anonamous
classes: the syntactic issues are exactly the same. The difficulty is
in extending it to methods, as opposed to functions. The only way
to distinguish a method from a function today is to observe that
methods are defined at the top level of a class; a def anywhere
else is a function (I think.)

John Roth
>
> Jonathan
>


Daniel Fackrell

unread,
Jul 30, 2002, 1:02:26 PM7/30/02
to
"John Roth" <john...@ameritech.net> wrote in message
news:ukddqte...@news.supernews.com...

Again, the problem is that Python must assume that when it sees code
indented further than the previous line, a single indent is intended. It
has no way of knowing how many indents you mean unless something is actually
indented to each level along the way.

In addition to that, indentation is currently ignored inside (), {}, [],
strings, and on lines following an escaped newline. Some of that could
change, perhaps, but it seems to me that it might break existing code.

I do see merit in this discussion, though, because I see class and def
statements as really being a shorthand for doing two things at once, namely
creating a function and then binding it to a name.

Admittedly, there are probably cases where the second part does not apply
all that well. Perhaps a case where you want a list or dict of functions
would be one such case. Binding to the name simply adds a step along the
way. Passing a callable object as a parameter to another callable object
would probably be another such case.

The issue quickly becomes readability, though. Would you want to be able to
do a complex multi-line def or class statement inside an assignment creating
a list, for example? And how would you do that without indentation?

funcList = [ Insert idea here ]

lambda in its current form does okay in cases like this. As an expression
it does not require indentation for anything, but it is also not allowed to
execute statements.

Ian Bicking

unread,
Jul 30, 2002, 2:46:16 PM7/30/02
to
On Tue, 2002-07-30 at 11:05, John Roth wrote:
> I tend to agree with you on that one, but it's a matter of style. I
> observe
> that e.g. Smalltalk style does anonymous code blocks all over the place.

I've seen people argue that you can do all the same things with
iterators as Smalltalk does with code blocks. And, really, it's not as
though Smalltalk has truly novel control structures -- everything still
boils down to while, for, and if. Smalltalk does give you easy
callbacks, though.

> There's no reason my proposal couldn't be extended to anonamous
> classes: the syntactic issues are exactly the same. The difficulty is
> in extending it to methods, as opposed to functions. The only way
> to distinguish a method from a function today is to observe that
> methods are defined at the top level of a class; a def anywhere
> else is a function (I think.)

A method is just a function that is bound to a class variable. So you
can do something like:

class X:
pass

X.func = lambda self, x: x * 2
x = X()
x.func(10)
==> 20

In fact, you can even do:

class X:
func = lambda self, x: x * 2


Ian

John Roth

unread,
Jul 30, 2002, 7:18:42 PM7/30/02
to

"Daniel Fackrell" <unle...@DELETETHIS.learn2think.org> wrote in
message news:3d46c6a2$1...@hpb10302.boi.hp.com...

This is quite true, however what I meant to convey (and don't seem
to have done a very good job of it) is that since you need two dedents
to close the figure (one to end the def (or class) and one to end the
enclosing expression) for symetry you need two indents. The compiler,
in fact, wouldn't (and shouldn't) be able to tell the difference, but I
presume that
syntax aware editors might be able to. I said two indents not because
of compiler concerns, but because of syntax aware editor concerns.

> In addition to that, indentation is currently ignored inside (), {},
[],
> strings, and on lines following an escaped newline. Some of that
could
> change, perhaps, but it seems to me that it might break existing code.

I don't see how it would break anything. The presence of 'def' or
'class'
would cause a shift into 'statement' mode. Those two reserved words are
not currently allowed within statements, only at the statement level.

> I do see merit in this discussion, though, because I see class and def
> statements as really being a shorthand for doing two things at once,
namely
> creating a function and then binding it to a name.

That's exactly the point.

> Admittedly, there are probably cases where the second part does not
apply
> all that well. Perhaps a case where you want a list or dict of
functions
> would be one such case. Binding to the name simply adds a step along
the
> way. Passing a callable object as a parameter to another callable
object
> would probably be another such case.

Well, that's what's significant about anonymous functions. The inline
definition
results in the function object, which then has to be consumed by
something
that takes a function object and uses it. The statement version binds
the
function or class object to a name as part of it's execution.

> The issue quickly becomes readability, though. Would you want to be
able to
> do a complex multi-line def or class statement inside an assignment
creating
> a list, for example? And how would you do that without indentation?

I suppose you could. Again, if the list is supposed to contain
references to
function objects, I don't see why not.


>
> funcList = [ Insert idea here ]

# notice that the indentation isn't very obvious - problems with OE
funcList = [ def (a, b):
print a # indented 20 spaces
print b # indented 20 spaces
, def (a, b): # indented 16 spaces
globalA = a # indented 20 spaces
globalB = b # indented 20 spaces
] # indented 12 spaces

Does this make sense?

>
> lambda in its current form does okay in cases like this. As an
expression
> it does not require indentation for anything, but it is also not
allowed to
> execute statements.

Well, yes. And lambda generally does quite well for short functions.
The idea that inline functions should be short has a great number of
adherents.

John Roth

Huaiyu Zhu

unread,
Jul 30, 2002, 6:37:53 PM7/30/02
to
Daniel Fackrell <unle...@DELETETHIS.learn2think.org> wrote:
>"John Roth" <john...@ameritech.net> wrote in message
>news:ukddqte...@news.supernews.com...
>> The reason I say "indenting 2" is that you need two
>> dedents to make it work: one to close the def, which does
>> not have it's own indent, and one to finish off the expression
>> in which the def is imbedded.
>
>Again, the problem is that Python must assume that when it sees code
>indented further than the previous line, a single indent is intended. It
>has no way of knowing how many indents you mean unless something is actually
>indented to each level along the way.

I don't quite get the idea why it has to indent 2. See examples below.

>In addition to that, indentation is currently ignored inside (), {}, [],
>strings, and on lines following an escaped newline. Some of that could
>change, perhaps, but it seems to me that it might break existing code.
>
>I do see merit in this discussion, though, because I see class and def
>statements as really being a shorthand for doing two things at once, namely
>creating a function and then binding it to a name.
>
>Admittedly, there are probably cases where the second part does not apply
>all that well. Perhaps a case where you want a list or dict of functions
>would be one such case. Binding to the name simply adds a step along the
>way. Passing a callable object as a parameter to another callable object
>would probably be another such case.

Here's an example to exand on the idea.

a = {
'func1': def (x,y):
lots of things
more things
return x+y
'func2': def (x,y):
lots of things
more things
return x-y
'func3': def (x,y):
lots of things
more things
return x-y
}

For vertical scoping, it is not necessary to separate items with commas.

>The issue quickly becomes readability, though. Would you want to be able to
>do a complex multi-line def or class statement inside an assignment creating
>a list, for example? And how would you do that without indentation?
>
>funcList = [ Insert idea here ]

This does not look too bad, although it does take a while to get used to.
For simple functions still lambdas look better.

curries = [
def (x):
return def (x,y):
return x+y

def (x):
f = def (x,y):
return x-y
return f

lambda x: lambda y: x*y,

class:
def __init__(self, x):
self.x = x
def __call__(self, y):
return x/y
]


Huaiyu

John Roth

unread,
Jul 30, 2002, 7:22:50 PM7/30/02
to

"Ian Bicking" <ia...@colorstudy.com> wrote in message
news:mailman.102805486...@python.org...

> On Tue, 2002-07-30 at 11:05, John Roth wrote:
> > I tend to agree with you on that one, but it's a matter of style. I
> > observe
> > that e.g. Smalltalk style does anonymous code blocks all over the
place.
>
> I've seen people argue that you can do all the same things with
> iterators as Smalltalk does with code blocks. And, really, it's not
as
> though Smalltalk has truly novel control structures -- everything
still
> boils down to while, for, and if. Smalltalk does give you easy
> callbacks, though.
>
> > There's no reason my proposal couldn't be extended to anonymous

> > classes: the syntactic issues are exactly the same. The difficulty
is
> > in extending it to methods, as opposed to functions. The only way
> > to distinguish a method from a function today is to observe that
> > methods are defined at the top level of a class; a def anywhere
> > else is a function (I think.)
>
> A method is just a function that is bound to a class variable. So you
> can do something like:
>
> class X:
> pass
>
> X.func = lambda self, x: x * 2
> x = X()
> x.func(10)
> ==> 20
>
> In fact, you can even do:
>
> class X:
> func = lambda self, x: x * 2

Unfortunately, that won't work. The word 'self' is not
magic - using it doesn't convert a function to a method.

On the other hand, if 'self' was the name assigned
to the instance in the enclosing method definition, it
would acomplish just about everything required. I suspect
there are a few corner cases it wouldn't handle, to
the confusion of all and sundry.

Someone who knows the language in more depth
than I do would have to comment on that.

John Roth

Ian Bicking

unread,
Jul 30, 2002, 8:53:38 PM7/30/02
to
On Tue, 2002-07-30 at 18:22, John Roth wrote:
> > A method is just a function that is bound to a class variable. So you
> > can do something like:
> >
> > class X:
> > pass
> >
> > X.func = lambda self, x: x * 2
> > x = X()
> > x.func(10)
> > ==> 20
> >
> > In fact, you can even do:
> >
> > class X:
> > func = lambda self, x: x * 2
>
> Unfortunately, that won't work. The word 'self' is not
> magic - using it doesn't convert a function to a method.

Fortunately it does work! You didn't read my first sentence. Those
(working) examples don't rely on the name "self" in the argument list.
They rely on the fact that a function is being put in a *class*
attribute (this doesn't work the same way if you put it in an instance
attribute).

Ian

Bryan Olson

unread,
Jul 30, 2002, 11:33:03 PM7/30/02
to
Ian Bicking wrote:

> I've seen people argue that you can do all the same things with
> iterators as Smalltalk does with code blocks. And, really, it's not as
> though Smalltalk has truly novel control structures -- everything still
> boils down to while, for, and if.

Decades before anyone implemented a programming language, Alonzo Church
boiled all the control structures down to just one: lambda.


--Bryana

Ian Bicking

unread,
Jul 31, 2002, 2:26:15 AM7/31/02
to

And Smalltalk *pretends* to implement something like the lambda calculus
-- but deep down, they had to use the same if statements we all use (for
performance reasons).

but-they're-all-turing-equivalently y'rs,
Ian

Kristian Ovaska

unread,
Jul 31, 2002, 5:05:29 AM7/31/02
to
JB <j...@hotmail.com>:
>(1) Why are back ticks a failure? I love them.

In addition to the problems others have pointed out, on my (Finnish)
keyboard I have to press Shift+ด+Space if I want a single back tick.
There are two ticks on the same key, back and forward, and I never use
either.

In English the traditional way to quote is ``like thisดด or `like
thisด, right? Here it's just "like this" or 'like this'.

--
Kristian Ovaska <kristia...@helsinki.fi>

James J. Besemer

unread,
Jul 31, 2002, 6:17:26 AM7/31/02
to

Ian Bicking wrote:

> > Decades before anyone implemented a programming language, Alonzo Church
> > boiled all the control structures down to just one: lambda.

Lambda and the Lambda Calculus have nothing to
do with "control structures," per se. The lambda
notation itself allowed the definition of True and False,
predicates and a conditional expression, the value of
which is one of two sub expressions based on a
governing predicate. Technically, however, there's
no 'control,' as everything was evaluated, even the
sub expression that was discarded. There is no looping
either, only recursive applications of lambda.

Conditional expression and recursion have some
vague similarities to if/then/else and while, respectively.
But in a purely functional language like the Lambda
Calculus, it seems a gross distortion to call them
'control structures'. When everything is an expression,
there's no "flow" to "control".

Lisp actually added "PROG" and other constructs as
alternatives to lambda in order to overcome this
limitation of pure lambda forms.

> And Smalltalk *pretends* to implement something like the lambda calculus
> -- but deep down, they had to use the same if statements we all use (for
> performance reasons).

I don't see why you say "pretends". Smalltalk IMO
actually does an excellent job generalizing the notion
of Lambda and integrating it with arbitrary sequences
of code.

Smalltalk's "blocks" are more powerful than Python's
Lambda and even Church's Lambda notation. Actually,
in function they resemble some of the extensions proposed
earlier in this thread, in that they may appear anywhere
an expression may be used, they associate a formal
argument list with an arbitrary statement sequence,
they optionally may be assigned to a variable and
they can be evaluated at a later time given an actual
arg list. This language design task was simplified by
the fact that the executable portion of Smalltalk consists
of sequences of message sends (which essentially are
expressions).

Smalltalk code "block":

[ :x :y | sequence of expressions in x and y and others ]

The block can be assigned to a name:

egBlock := [ :x :y | sequence of expressions in x and y and others ]

and then evaluated at a later time:

egBlock value: 3 value: 5

Smalltalk's control structures have no pretension
whatsoever to be related to lambda (or anything
else I've ever seen before). Some examples:

count timesRepeat: [ block of code ]

[ count <= max ]
whileTrue: [ another block ]

x < 10
ifTrue: [ true block ]
ifFalse: [ false block ]

Furthermore, I dare say Smalltalk's choice of these
constructs were dictated by the language's universal
object/message metaphor, having little or no bearing
on performance.

Regards

--jb

--
James J. Besemer 503-280-0838 voice
http://cascade-sys.com 503-280-0375 fax
mailto:j...@cascade-sys.com

John Roth

unread,
Jul 31, 2002, 9:24:47 AM7/31/02
to

"Huaiyu Zhu" <hua...@gauss.almadan.ibm.com> wrote in message
news:slrnake5a1...@gauss.almadan.ibm.com...

That works nicely, and you're right, you don't need two
dedents in this case, so you don't need two (virtual) indents either.

> For vertical scoping, it is not necessary to separate items with
commas.

Is this valid Python in general, or is this another change to the
syntax?

> >The issue quickly becomes readability, though. Would you want to be
able to
> >do a complex multi-line def or class statement inside an assignment
creating
> >a list, for example? And how would you do that without indentation?
> >
> >funcList = [ Insert idea here ]
>
> This does not look too bad, although it does take a while to get used
to.
> For simple functions still lambdas look better.
>
> curries = [
> def (x):
> return def (x,y):
> return x+y
>
> def (x):
> f = def (x,y):
> return x-y
> return f
>
> lambda x: lambda y: x*y,
>
> class:
> def __init__(self, x):
> self.x = x
> def __call__(self, y):
> return x/y
> ]

Another nice example. Thanks. Again, the commas
are missing, which may be a good thing, or it may
not.

John Roth


John Roth

unread,
Jul 31, 2002, 9:35:40 AM7/31/02
to

"Ian Bicking" <ia...@colorstudy.com> wrote in message
news:mailman.1028076887...@python.org...

I'm not certain of context here, because your reply didn't
associate properly with my original post, so if I wander a bit,
please excuse.

The issue I was addressing was putting an anonymous function
(or method) in an expression, without any fancy conditions. In other
words, putting it where you would normally want to - with lots
of other code within a class. I wasn't addressing a corner condition.

When you're writing a method in a class, and you want to
create an anonymous function within the code of that method,
how do you tell the compiler that you want a method instead?
That is the question.

It may turn out to have a trivial answer, but as I think I said in
the original post, my knowledge of the details of Python at
that level is insufficient. What I am certain of is that simply
saying 'self' as the first parameter isn't sufficient for the
compiler to mark it as a method (which is a different kind
of object than a function!)

What I'm not certain of is whether it matters.

John Roth
>
> Ian
>
>
>


Ian Bicking

unread,
Jul 31, 2002, 12:22:44 PM7/31/02
to
On Wed, 2002-07-31 at 08:35, John Roth wrote:
> The issue I was addressing was putting an anonymous function
> (or method) in an expression, without any fancy conditions. In other
> words, putting it where you would normally want to - with lots
> of other code within a class. I wasn't addressing a corner condition.
>
> When you're writing a method in a class, and you want to
> create an anonymous function within the code of that method,
> how do you tell the compiler that you want a method instead?
> That is the question.

There's no way that I know of, but that shouldn't be a big deal.
Typically you'll have to use nested scopes (to get self bound implicitly
in the lambda), or pass self in as a default parameter (e.g., lambda x,
self=self: ...)

Ian

Ian Bicking

unread,
Jul 31, 2002, 12:35:57 PM7/31/02
to
On Wed, 2002-07-31 at 05:17, James J. Besemer wrote:
> Smalltalk's control structures have no pretension
> whatsoever to be related to lambda (or anything
> else I've ever seen before). Some examples:
>
> count timesRepeat: [ block of code ]
>
> [ count <= max ]
> whileTrue: [ another block ]
>
> x < 10
> ifTrue: [ true block ]
> ifFalse: [ false block ]

Well, it looks a lot like lambda calculus, because True and False are
two different classes, with definitions like:
----
(True)
ifTrue: block
block value "This evaluates the passed block"

ifFalse: block
"do nothing"

(False)
ifTrue: block
"do nothing"

ifFalse: block
block value
----
This should remind one of true/false in lambda calculus (though
obviously with a very different notation).

But, at least in Squeak (and my impression is this is universal among
Smalltalk environments), ifTrue:/ifFalse: don't actually get passed as
method calls/messages. The compiler specifically looks for those
methods, and turns them into traditional if statements in the bytecode.
That is, you can't (usefully) implement ifTrue: in your own custom
class.

Ian

Huaiyu Zhu

unread,
Jul 31, 2002, 2:21:04 PM7/31/02
to
John Roth <john...@ameritech.net> wrote:
>
>> For vertical scoping, it is not necessary to separate items with
>commas.
>
>Is this valid Python in general, or is this another change to the
>syntax?

It's just what I think is necessary. I'm not sure if it fits the
current python parser, although it appears to be so for existing
structures like def, class, if, while.

Huaiyu

James J. Besemer

unread,
Jul 31, 2002, 4:16:05 PM7/31/02
to

Ian Bicking wrote:

> Well, it looks a lot like lambda calculus, because True and False are
> two different classes, with definitions like:

> This should remind one of true/false in lambda calculus (though


> obviously with a very different notation).

Narrowly interpreted, there is a similarity, in that both systems
build up their "control flow" abstractions from True and False,
as opposed to, say, COND. Further, they both define True
and False in terms of each language's fundamental abstraction
mechanism, class definitions in Smalltalk's case and and Lambda
expressions for Lambda Calculus.

However, the notations and the underlying abstractions are so
vastly different I find it hard to view them as anything but largely
unrelated. But maybe I'll feel differently tomorrow.

> The compiler specifically looks for those
> methods, and turns them into traditional if statements in the bytecode.

This is simply an optimization for speed. Most compilers also
handle special cases for small integer arithmetic. Even newer
ones compile direct to machine code instead of byte codes.

These compiler optimizations are completely optional. They
have nothing to do with the language design and certainly have
absolutely nothing to do with any purported difficulties implementing
Lambda or Smalltalk control structures.

If there's a weakness in the Language, it's that the fully general
hash table lookup for each and every operation (including small
integer arithmetic and trivial control structures) is extremely
expensive and an obvious hot spot to try to optimize.

> That is, you can't (usefully) implement ifTrue: in your own custom
> class.

Absolutely not true.

You can implement like methods in your own classes and it
will work just fine. Key is that Smalltalk's block construct
allows passing in as an argument unevaluated chunks of code,
which the method itself controls if/when to execute. The compiler
will recognize that the destination+method is not one of the
patterns it knows how to optimize so it will generate a fully
general message send. Ultimately your object will get the
ifTrue: message with it's block argument and you can evaluate
the block or not, depending on the instance's local state or whatever.

E.g., you define a method for your class by a method that does
a three-way branch:

ifZero: z ifGreater: g ifLesser: s
( state > 0 ) ifTrue: [ ^g value ]
( state < 0 ) ifFalse: [ ^s value ]
^z value

To call it:

myStateObj ifZero: [ zero block ]
ifGreater: [ greater block ]
ifLesser: [lesser block ]

You could even extend Numbers themselves to have this new
control flow construct.

Smalltalk's blocks ARE the language's Lambda equivalent, they
work quite well, and they're implemented fully generally at the
user level. They're one source of the language's incredible
flexibility and power.

John Roth

unread,
Jul 31, 2002, 4:31:48 PM7/31/02
to

"Huaiyu Zhu" <hua...@gauss.almadan.ibm.com> wrote in message
news:slrnakgake...@gauss.almadan.ibm.com...

It certainly looks nice, but I think it's a change to the
syntax for list and dictionary constructors, which
is a different issue.

John Roth
>
> Huaiyu


It is loading more messages.
0 new messages