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

Home Posts Topics Members FAQ

Replacement for lambda - 'def' as an expression?

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 as data, where you have a whole lot of functions
and it can be tedious to come up with a name for each one.

For example, my current hobby project is implementing pattern matching
similar to Prolog in Python. The dispatcher I am making allows you to
create "overloaded " versions of a function that take different patterns
as their input arguments, so that Simplify( (add, x, y) ) calls a
different method than Simplify( (log, x) ) -- in other words, the
choice of which code is executed is based on the structure of the tuple
that is passed into it. However, in order for this to work, I need to
be able to assign a block of Python code to a particular pattern, and
having to invent a named function for each pattern is a burden :)

Anyway, here's an example, then, of how 'def' could be used:

add = def( a, b ):
return a + b

The lack of a function name signals that this is an anonymous function.
The def keyword defines the function using the same syntax as always -
the arguments are in parentheses, and are unevaluated; The colon marks
the beginning of a suite.

In fact, it looks a lot like the existing lambda, with a couple of
differences:

1) It uses the familiar "def" keyword, which every Python beginner
understands, instead of the somewhat unfamiliar "lambda"
2) The arguments are enclosed in parentheses, instead of a bare tuple
followed by a colon, again reiterating the similarity to the normal
usage of "def".
3) The statements are a real suite instead of a pseudo-suite - they can
consist of multiple lines of statements.

Like all statements whose last argument is a suite, you can put the
body of the function on a single line:

add = def( a, b ): return a + b

(If this were Perl, you could also omit the "return", since in Perl the
last evaluated expression in the function body is what gets returned if
there's no explicit return statement.)

What about passing an anonymous function as an argument, which is the
most common case? This gets tricky, because you can't embed a suite
inside of an expression. Or can you?

The most powerful option would be to leverage the fact that you can
already do line breaks inside of parentheses. So the "def" keyword
would tell the parser to restart the normal indentation calculations,
which would terminate whenever an unmatched brace or paren was
encountered:

a = map(
(def( item ):
item = do_some_calcula tion( item )
return item
), list )

The one-liner version looks a lot prettier of course:

a = map( (def( item ): return item * item), list )

And it looks even nicer if we switch the order of the arguments around,
since you can now use the final paren of the enclosing function call to
terminate the def suite.

a = map( list, def( item ): return item * item )

Unfortunately, there's no other good way I can think of to signal the
end of the block of statements without introducing some radical new
language construct.

(Besides, if being an expression is good enough for 'yield', why
shouldn't def get the same privilege? :)

Sep 6 '05 #1
18 1535
Hallöchen!

"talin at acm dot org" <vi*****@gmail. com> writes:
[...]

Anyway, here's an example, then, of how 'def' could be used:

add = def( a, b ):
return a + b


I'm really not an expert in functional programming, so I wonder
what's the difference between "add = def" (assumed that it worked)
and "def add"?

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus ICQ 264-296-646
Sep 6 '05 #2
On Tue, 06 Sep 2005 12:19:21 +0200
Torsten Bronger wrote:
"talin at acm dot org" <vi*****@gmail. com> writes:
Anyway, here's an example, then, of how 'def' could be used:

add = def( a, b ):
return a + b


I'm really not an expert in functional programming, so I wonder
what's the difference between "add = def" (assumed that it worked)
and "def add"?


In the former case one could write

self.add[0] = def(a, b)
# etc.

--
jk
Sep 6 '05 #3
talin at acm dot org enlightened us with:
I'd be sad to see the notion of "anonymous functions" go
Same here. I think it's a beautyful concept, and very powerful. It
also allows for dynamic function creation in cases where a name would
not be available.
What about passing an anonymous function as an argument, which is
the most common case?


I don't really like that. The syntax is way too messy. Just the

funcref = def(args):
...

syntax would suffice for me.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Sep 6 '05 #4
en**********@os paz.ru wrote:
On Tue, 06 Sep 2005 12:19:21 +0200
Torsten Bronger wrote:

"talin at acm dot org" <vi*****@gmail. com> writes:
Anyway, here's an example, then, of how 'def' could be used:

add = def( a, b ):
return a + b


I'm really not an expert in functional programming, so I wonder
what's the difference between "add = def" (assumed that it worked)
and "def add"?

In the former case one could write

self.add[0] = def(a, b)
# etc.


If that's the issue, it might make more sense to extend def to take any
lvalue.

def self.add[0](a, b):
return a + b
Sep 6 '05 #5
Sybren Stuvel wrote:
It also allows for dynamic function creation in cases where a name
would not be available.


What cases are those?
Sep 6 '05 #6
Leif K-Brooks enlightened us with:
It also allows for dynamic function creation in cases where a name
would not be available.


What cases are those?


An example:

def generate_random izer(n, m):
randomizer = def(x):
return x ** n % m

return randomizer

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Sep 6 '05 #7
Sybren Stuvel <sy*******@YOUR thirdtower.com. imagination> writes:
An example:

def generate_random izer(n, m):
randomizer = def(x):
return x ** n % m

return randomizer


You're a little bit confused; "name" doesn't necessarily mean "persistent
name". You could write the above as:

def generate_random izer (n, m):
def randomizer(x):
return pow(x, n, m)
return randomizer
Sep 6 '05 #8
D H
talin at acm dot org wrote:
I've been reading about how "lambda" is going away in Python 3000 (or


See the page built from earlier threads about this:
http://wiki.python.org/moin/AlternateLambdaSyntax

Your syntax is the same used in boo: http://boo.codehaus.org/Closures
Sep 6 '05 #9

"talin at acm dot org" <vi*****@gmail. com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
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 as data, where you have a whole lot of functions
and it can be tedious to come up with a name for each one.
Either reuse names or 'index' them: f0, f1, f2, ...
add = def( a, b ):
return a + b
The difference between this and def add(a,b): return a+b would be the
finding of .func_name to an uninformative generic tag (like '<lambda.>')
versus the informative 'add'.
I need to be able to assign a block of Python code to a particular
pattern,
How about (untested -- I have never actually written a decorator, and am
following a remembered pattern of parameterized decorators) :

patcode = {}
def pat(pattern): # return decorator that registers f in patcode
def freg(f):
f.func_name = 'pat: <%s>' % pattern # optional but useful for debug
patcode[pattern] = f
# no return needed ? since def name is dummy
return freg

@pat('pattern1' )
def f(): <code for pattern 1>

@pat('pattern2' )
def f(): <code> for pattern 2>

etc

or define freg(f,pat) and call freg *after* each definition
having to invent a named function for each pattern is a burden :)


But you do not *have to* ;-)
or rather, you can replace func_name with a useful tag as suggested above.

Terry J. Reedy


Sep 6 '05 #10

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

Similar topics

4
1714
by: Michael Foord | last post by:
I'm starting to read through the developer works article on Functional Programming - http://www-106.ibm.com/developerworks/library/l-prog.html It starts by giving some basic examples using lambda. What I'm wondering is what's the actual difference between these two forms ? pr = lambda s:s *and* def pr(s): return s
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. :-)
6
1493
by: George Yoshida | last post by:
Just out of curiosity, is there any way to get the name of a lambda expression? Lambdas are anonymous functions, so it's a stupid idea to get the name of it. But if it's possible, how could I? Let's take a simple example: foo = lambda:None foo.__name__(or foo.func_name) returns '<lambda>'. I'm looking for a way to return 'foo', instead of '<lambda>'.
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.
30
2169
by: Mike Meyer | last post by:
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...
267
10797
by: Xah Lee | last post by:
Python, Lambda, and Guido van Rossum Xah Lee, 2006-05-05 In this post, i'd like to deconstruct one of Guido's recent blog about lambda in Python. In Guido's blog written in 2006-02-10 at http://www.artima.com/weblogs/viewpost.jsp?thread=147358
26
2724
by: brenocon | last post by:
Hi all -- Compared to the Python I know and love, Ruby isn't quite the same. However, it has at least one terrific feature: "blocks". Whereas in Python a "block" is just several lines of locally-scoped-together code, in Ruby a "block" defines a closure (anonymous function). To avoid confusion let's call them Ruby block-closures. I see them as just a syntax for defining
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...
1
9342
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,...
0
6081
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
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...
0
4888
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3323
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
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.