I know, lambda bashing (and defending) in the group is one of the most
popular ways to avoid writing code. However, while staring at some Oz
code, I noticed a feature that would seem to make both groups happy -
if we can figure out how to avoid the ugly syntax.
This proposal does away with the well-known/obscure "lambda"
keyword. It gives those who want a more functional lambda what they
want. It doesn't add any new keywords. It doesn't add any new magic
characters, though it does add meaning to an existing one. That could
be replaced by a new magic token, or adding magic meaning to a
non-magic token. It breaks no old code either way.
I haven't really worked out all the implications; I just wanted to
throw it out and see what everyone else thought about it. As a
result, the code examples tend to be ugly.
As previously hinted, this feature is lifted from Oz.
Currently, class and functions definitions consist of a keyword -
either "class" or "def" - followed by a name, a header, then code. The
code is compiled into an object, and the name is bound to that object.
The proposal is to allow name to be a non-name (or rare name)
token. In this case, the code is compiled and the resulting object is
used as the value of the class/def expression.
My choice for the non-name token is "@". It's already got magic
powers, so we'll give it more rather than introducing another token
with magic powers, as the lesser of two evils.
Rewriting a canonical abuse of lambda in this idiom gives:
myfunc = def @(*args):
return sum(x + 1 for x in args)
In other words, this is identical to:
def myfunc(*args):
return sum(x + 1 for x in args)
We can write the same loop with logging information as:
sum(def @(arg):
print "Bumping", arg
return arg + 1
(x) # '(' at the same indent level as def, to end the definition
for x in stuff)
A more useful example is the ever-popular property creation without
cluttering the class namespace:
class Spam(object):
myprop = property(fget = def @(self):
return self._propertie s['myprop']
,
fset = def @(self, value):
self._propertie s['myprop'] = value
,
fdel = def @(self)
del self._propertie s['myprop']
,
doc = "Just an example")
This looks like the abuse of lambda case, but these aren't
assignments, they're keyword arguments. You could leave off the
keywords, but it's not noticably prettier. fget can be done with a
lambda, but the the others can't.
Giving clases the same functionality seems to be the reasonable thing
to do. It's symmetric. And if anonymous function objects are good,
then anonymous class objects ought to be good as well.
<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. 30 2155
Mike Meyer wrote: My choice for the non-name token is "@". It's already got magic powers, so we'll give it more rather than introducing another token with magic powers, as the lesser of two evils.
Doesn't work. The crux of your change isn't introducing a meaning to @
(and honestly, I prefer _), it's that you change the 'define block' from
a compound_stmt (funcdef) (see www.python.org/doc/current/ref/compound.html) to an expression_stmt
(expresion). This change would allow some really damn weird things, like:
if def _(x,y):
return x**2 - y**2
(5,-5): # ?! How would you immediately call this 'lambda-like'?[1]
print 'true'
else:
print 'false'
[1] -- yes, it's generally stupid to, but I'm just pointing out what has
to be possible.
Additionally, Python's indenting Just Doesn't Work Like That; mandating
an indent "after where the def came on the previous line" (as you do in
your example, I don't know if you intend for it to hold in your actual
syntax) wouldn't parse right -- the tokenizer generates INDENT and
DEDENT tokens for whitespace, as I understand it.
My personal favourite is to replace "lambda" entirely with an
"expression comprehension", using < and > delimeters. It just looks
like our existing list and generator comprehensions, and it doesn't use
'lambda' terminology which will confuse any newcomer to Python that has
experience in Lisp (at least it did me).
g = <x**2 with (x)>
g(1) == 1
Basically, I'd rewrite the Python grammar such that:
lambda_form ::= "<" expression "with" parameter_list ">"
Biggest change is that parameter_list is no longer optional, so
zero-argument expr-comps would be written as <expr with ()>, which makes
a bit more sense than <expr with>.
Since "<" and ">" aren't ambiguous inside the "expression " state, this
shouldn't make the grammar ambiguous. The "with" magic word does
conflict with PEP-343 (semantically, not syntactically), so "for" might
be appropriate if less precise in meaning.
Christopher Subich <sp************ ****@block.subi ch.spam.com> writes: My personal favourite is to replace "lambda" entirely with an "expression comprehension", using < and > delimeters.
But how does that let you get more than one expression into the
anonymous function?
Christopher Subich wrote: g = <x**2 with (x)> g(1) == 1
Basically, I'd rewrite the Python grammar such that: lambda_form ::= "<" expression "with" parameter_list ">"
Biggest change is that parameter_list is no longer optional, so zero-argument expr-comps would be written as <expr with ()>, which makes a bit more sense than <expr with>.
Since "<" and ">" aren't ambiguous inside the "expression " state, this shouldn't make the grammar ambiguous. The "with" magic word does conflict with PEP-343 (semantically, not syntactically), so "for" might be appropriate if less precise in meaning.
What kind of shenanigans must a parser go through to translate:
<x**2 with(x)><<x**3 with(x)>
this is the comparison of two functions, but it looks like a left-
shift on a function until the second with is encountered. Then
you need to backtrack to the shift and convert it to a pair of
less-thans before you can successfully translate it.
--Scott David Daniels Sc***********@A cm.Org
On 2005-07-30, Scott David Daniels <Sc***********@ Acm.Org> wrote: Christopher Subich wrote: g = <x**2 with (x)> g(1) == 1
Basically, I'd rewrite the Python grammar such that: lambda_form ::= "<" expression "with" parameter_list ">"
Biggest change is that parameter_list is no longer optional, so zero-argument expr-comps would be written as <expr with ()>, which makes a bit more sense than <expr with>.
Since "<" and ">" aren't ambiguous inside the "expression " state, this shouldn't make the grammar ambiguous. The "with" magic word does conflict with PEP-343 (semantically, not syntactically), so "for" might be appropriate if less precise in meaning. What kind of shenanigans must a parser go through to translate: <x**2 with(x)><<x**3 with(x)>
this is the comparison of two functions, but it looks like a left- shift on a function until the second with is encountered. Then you need to backtrack to the shift and convert it to a pair of less-thans before you can successfully translate it.
I'm just worming my way into learning Lisp, but this seems to be a
perfect example of everything I'm seeing so far. The compiler should
do all sorts of gymnastics and contortions. Make the compiler/interpreter
as complex as possible, to handle any freaky thing a programmer can
invent.
Which does not, in the least, imply that the same attitude should apply toward
python.
I read this thread and my brain hurts. Python code should *never* do this.
Tim Peters (let's all bow down, we're not worthy <g>) might write some code that
I can't quite follow. But at least it's obvious. He doesn't suddenly introduce
an entirely new syntax for the sake of "hey, this would be cool." Or maybe
"It'd be much more simple if we made everyone use more C-like syntax." Or...
wherever you were going with this. This <x**2 with(x)><<x**3 with(x)>
is precisely the kind of code that I got into python to avoid.
I happen to like nice, simple, readable code. Maybe I'm just old and grumpy.
Looking at that line, I get the same "This is just ugly" feel that I get when
I at perl. Some note from other pieces in this thread. Things about $_ or
what-not.
Personally, I can't recall any decent programmer I know who objects to actually
writing out a variable name. In fact, I don't know a single "real" programmer
(this is one who writes programs he intends to look at again in, say, 3 weeks)
who doesn't insist on writing "real" variable names.
(Heh. I'll probably read through some Guido code next week that totally proves
me wrong <g>...such is life).
--Scott David Daniels Sc***********@A cm.Org
--
Liberty means responsibility. That is why most men dread it.
- George Bernard Shaw
Scott David Daniels <Sc***********@ Acm.Org> wrote: What kind of shenanigans must a parser go through to translate: <x**2 with(x)><<x**3 with(x)>
this is the comparison of two functions, but it looks like a left- shift on a function until the second with is encountered. Then you need to backtrack to the shift and convert it to a pair of less-thans before you can successfully translate it.
C++ solves this exact problem quite reasonably by having a greedy
tokenizer. Thus, that would always be a left shift operator. To make it
less than and a function, insert a space:
<x**2 with(x)>< <x**3 with(x)>
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
James Richards <ro*****@govtab use.com> writes: Personally, I can't recall any decent programmer I know who objects to actually writing out a variable name. In fact, I don't know a single "real" programmer (this is one who writes programs he intends to look at again in, say, 3 weeks) who doesn't insist on writing "real" variable names.
The issue is whether you want to name every intermediate result in
every expression.
sum = a + b + c + d + e
is a lot nicer than
x1 = a + b
x2 = c + d
x3 = x1 + e
sum = x2 + x3
the language has nicely kept all those intermediate results anonymous.
Python has first-class functions, which, like recursion, is a powerful
idea that takes some getting used to. They let you say things like
def derivative(f, t, h=.00001): # evaluate f'(t) numerically
return (f(t+h) - f(t)) / h
dy_dt = derivative(cos, 0.3) # approx. -sin(0.3)
With anonymous functions, you can also say:
dy_dt = derivative(lamb da x: sin(x)+cos(x), 0.3) # approx. cos(.3)-sin(.3)
Most Python users have experience with recursion before they start
using Python, so they don't see a need for extra keywords to express
it. Those not used to first-class functions (and maybe some others)
seem to prefer extra baggage. For many of those used to writing in
the above style, though, there's nothing confusing about using a
lambda there instead of spewing extra verbiage to store that
(lambda x: sin(x)+cos(x)) function in a named variable before
passing it to another function.
Tim Roberts schrieb: Scott David Daniels <Sc***********@ Acm.Org> wrote: What kind of shenanigans must a parser go through to translate: <x**2 with(x)><<x**3 with(x)>
this is the comparison of two functions, but it looks like a left- shift on a function until the second with is encountered. Then you need to backtrack to the shift and convert it to a pair of less-thans before you can successfully translate it.
C++ solves this exact problem quite reasonably by having a greedy tokenizer. Thus, that would always be a left shift operator. To make it less than and a function, insert a space: <x**2 with(x)>< <x**3 with(x)> -- - Tim Roberts, ti**@probo.com Providenza & Boekelheide, Inc.
Python does have such a greedy/longest match tokenizer too: 2 .__add__(3) # insert whitespace before dot
5
2.__add__(3) # 2. is a float
-> Exception
Kay
why (x**2 with(x))<(x**3 with(x)) is not taken in consideration?
If 'with' must be there (and substitue 'lambda:') then at least the
syntax is clear.IMO Ruby syntax is also clear.
_______________ _______________ _____
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it
Mike Meyer wrote: Rewriting a canonical abuse of lambda in this idiom gives:
myfunc = def @(*args): return sum(x + 1 for x in args)
Nice proposal. Technically you don't need the @ there, it is
superfluous. But then again so is the colon, so whatever floats your boat.
class Spam(object): myprop = property(fget = def @(self): return self._propertie s['myprop'] , fset = def @(self, value): self._propertie s['myprop'] = value , fdel = def @(self) del self._propertie s['myprop'] , doc = "Just an example")
I think the anonymous lambdas need to be outside the parentheses to be
parsable. Maybe like this:
class Spam(object):
myprop = property(fget, fset, fdel, doc="just an example"):
where fget = def (self):
.........
where fset = def (self):
.........
where fdel = def (self):
...........
As you can see, it doesn't save much over the traditional way since you
have to name the "anonymous" lambdas anyway. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Oliver Fromme |
last post by:
Hi,
I'm trying to write a Python function that parses
an expression and builds a function tree from it
(recursively).
During parsing, lambda functions for the the terms
and sub-expressions are constructed on the fly.
Now my problem is lazy evaluation. Or at least I
think it is. :-)
|
by: Stephen Thorne |
last post by:
Hi guys,
I'm a little worried about the expected disappearance of lambda in
python3000. I've had my brain badly broken by functional programming
in the past, and I would hate to see things suddenly become harder
than they need to be.
An example of what I mean is a quick script I wrote for doing certain
actions based on a regexp, which I will simlify in this instance to
make the pertanant points more relevent.
|
by: Steven Bethard |
last post by:
I thought it might be useful to put the recent lambda threads into
perspective a bit. I was wondering what lambda gets used for in "real"
code, so I grepped my Python Lib directory. Here are some of the ones I
looked, classified by how I would rewrite them (if I could):
* Rewritable as def statements (<name> = lambda <args>: <expr> usage)
These are lambdas used when a lambda wasn't needed -- an anonymous
function was created with...
|
by: Tom Anderson |
last post by:
Comrades,
During our current discussion of the fate of functional constructs in
python, someone brought up Guido's bull on the matter:
http://www.artima.com/weblogs/viewpost.jsp?thread=98196
He says he's going to dispose of map, filter, reduce and lambda. He's
going to give us product, any and all, though, which is nice of him.
|
by: talin at acm dot org |
last post by:
I've been reading about how "lambda" is going away in Python 3000 (or
at least, that's the stated intent), and while I agree for the most
part with the reasoning, at the same time I'd be sad to see the notion
of "anonymous functions" go - partly because I use them all the time.
Of course, one can always create a named function. But there are a lot
of cases, such as multimethods / generics and other scenarios where
functions are treated...
| |
by: Xah Lee |
last post by:
A Lambda Logo Tour
(and why LISP languages using λ as logo should not be looked upon
kindly)
Xah Lee, 2002-02
Dear lispers,
The lambda character λ, always struck a awe in me, as with other
mathematical symbols. In my mind, i imagine that those obscure math
|
by: Kaz Kylheku |
last post by:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.
So for the last 15 minutes I applied myself to this problem and come up
with this off-the-wall proposal for you people. Perhaps this idea has
been proposed before, I don't know.
The solutions I have seen all assume that the lambda must be completely
inlined within the...
|
by: globalrev |
last post by:
i have a rough understanding of lambda but so far only have found use
for it once(in tkinter when passing lambda as an argument i could
circumvent some tricky stuff).
what is the point of the following function?
def addn(n):
return lambda x,inc=n: x+inc
if i do addn(5) it returns
|
by: Tim H |
last post by:
Compiling with g++ 4:
This line:
if_then_else_return(_1 == 0, 64, _1)
When called with a bignum class as an argument yields:
/usr/include/boost/lambda/if.hpp: In member function 'RET
boost::lambda::lambda_
functor_base<boost::lambda::other_action<boost::lambda::ifthenelsereturn_action>
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |