473,750 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A replacement for lambda

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.
Jul 29 '05
30 2169
D H <no@spam> writes:
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.


It saves polluting the surrounding namespace with superfluous variables
that aren't going to be used again.
Jul 30 '05 #11
Christopher Subich <spam.csubich+b l...@block.subi ch.spam.com> writes:
Basically, I'd rewrite the Python grammar such that:
lambda_form ::= "<" expression "with" parameter_list ">"


I do prefer my parameter list to come before the expression. It would
remain consistant with simple function definitions.

- Cheers, Paddy.

Jul 30 '05 #12
on 30.07.2005 10:20 Paolino said the following:
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.


I am sorry if this has already been proposed (I am sure it has).

Why not substitue python-lambdas with degenerated generator expressions::

(lambda x: func(x)) == (func(x) for x)

i.e. a one time callable generator expression (missing the `in` part).
The arguments get passed into the generator, I am sure that can be
combined with the PEP about passing args and Exceptions into a generator.

Jul 30 '05 #13
Stefan Rank <st*********@of ai.at> writes:
I am sorry if this has already been proposed (I am sure it has).
Why not substitue python-lambdas with degenerated generator expressions::

(lambda x: func(x)) == (func(x) for x)


I don't think I've seen that one before, and FWIW it's kind of cute.

But what's wrong with leaving lambdas the way they are? Anyone who can
understand generator expressions can understand lambda. I don't see any
point in trying to improve on lambda, without actually fixing its main
problem, which is the inability to create multi-statement closures.
Jul 30 '05 #14
Mike Meyer schrieb:
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.


Mike,

in modern functional language design one starts with certain lambda
expressions and add syntax sugar ( operational / statement syntax ) for
constructs based on them. In Python statement- and expression syntax
were introduced seperately. Pythons lambda is simply the symptom of
this separation. Now you suggest ( not the first time on this list or
at python-dev ) to put statements into expressions leading to a strange
syntax and conflicting with Pythons indentation rules.

Another way to deal with the restrictions of lambda is going the other
way round and simply propose expression syntax for conds and
assignments.

Using guards '||' and the keyword 'then' for conditional expressions:

( || x>=0 then f(x) || True then f(-x) )

Or shorter dropping 'then' in the second condition:

( || x>=0 then f(x) || f(-x) )

Both translates to:

if x>=0:
f(x)
else:
f(-x)

Using a reverse arrow for assignments:

x <- y

For loops can be replaced by functional constructs ( use map() or a
list/generator comprehension ).

Finally the lambda keyword can be replaced by expressional syntax e.g.
( EXPR from ARGS ):

Examples:
f = ( || x>=0 then f(x) || True then f(-x) from (x,) )
g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,))

Kay

Jul 30 '05 #15
"Kay Schluehr" <ka**********@g mx.net> writes:
Examples:
f = ( || x>=0 then f(x) || True then f(-x) from (x,) )
g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,))


Is this an actual language? It looks sort of like CSP. Python
with native parallelism, mmmmm.
Jul 30 '05 #16
Paul Rubin wrote:
"Kay Schluehr" <ka**********@g mx.net> writes:
Examples:
f = ( || x>=0 then f(x) || True then f(-x) from (x,) )
g = ( || x< 0 then self._a <-x || self._a <- 0 from (x,))


Is this an actual language? It looks sort of like CSP. Python
with native parallelism, mmmmm.


The syntax was inspired by OCamls pattern matching syntax:

match object with
pattern1 -> result1
| pattern2 -> result2
| pattern3 -> result3
...

But for Python we have to look for an expression not a statement
syntax. In order to prevent ambiguities I used a double bar '||'
instead of a single one.

Kay

Jul 30 '05 #17
Stefan Rank wrote:
on 30.07.2005 10:20 Paolino said the following:
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.


I am sorry if this has already been proposed (I am sure it has).

Why not substitue python-lambdas with degenerated generator expressions::

(lambda x: func(x)) == (func(x) for x)

i.e. a one time callable generator expression (missing the `in` part).
The arguments get passed into the generator, I am sure that can be
combined with the PEP about passing args and Exceptions into a generator.


It's hard to spot, and it's too different to a genexp to have such a similar
syntax.

Reinhold
Jul 30 '05 #18
I understand that there are a number of people who wish to remove
lambda entirely from the language. Nevertheless, I find it a useful
and powerful tool in actual development.

Any replacement must support the following: *delayed evaluation*.

I need a convenient (def is not always convenient) way of saying,
"don't do this now". That is why I use lambda.

-- Seth Nielson

On 7/30/05, Reinhold Birkenfeld <re************ ************@wo lke7.net> wrote:
Stefan Rank wrote:
on 30.07.2005 10:20 Paolino said the following:
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.


I am sorry if this has already been proposed (I am sure it has).

Why not substitue python-lambdas with degenerated generator expressions::

(lambda x: func(x)) == (func(x) for x)

i.e. a one time callable generator expression (missing the `in` part).
The arguments get passed into the generator, I am sure that can be
combined with the PEP about passing args and Exceptions into a generator.


It's hard to spot, and it's too different to a genexp to have such a similar
syntax.

Reinhold
--
http://mail.python.org/mailman/listinfo/python-list

Jul 30 '05 #19
Seth Nielson <se****@gmail.c om> writes:
Any replacement must support the following: *delayed evaluation*.

I need a convenient (def is not always convenient) way of saying,
"don't do this now". That is why I use lambda.


How's this: f{args} (curly braces instead of parens) is the same as
f(lambda: args).

Examples:

launch_thread{t argetfunc(a,b,c )}

b = Button{callback =pressed()} # Button remembers callback()

def ternary(cond, x, y):
if cond(): return x()
else: return y()

sign_of_a = ternary{a < 0, -1, 1}
etc.
Jul 30 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

53
3689
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. :-)
63
3404
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.
26
3498
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...
181
8867
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.
18
1535
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...
4
2630
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
23
5329
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...
21
1850
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
1
2629
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>
0
9001
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8838
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9256
tracyyun
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...
0
8263
agi2029
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...
1
6808
isladogs
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...
0
4716
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...
2
2807
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2226
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.