Hello,
I'm new on this list and in python.
It seems python has some interesting concept of "ad hoc" function
which I'm trying to understand without much success.
Take the following code for example:
"""
>>def make_incremento r(n):
.... return lambda x: x + n
....
>>f = make_incremento r(42) f(0)
42
>>f(1)
43
"""
I really don't understand whats going on here.
On the first instantiating of the object "f" where does "x" gets it's
value? Or is it evaluated as 0? ie "x: 0 + 42"
And what is the "f" object? An integer? a pointer? an Object?
I'm coming from the C world...
Could some please try (if even possible) to implement the above code
without using "lambda" I believe it would help me grasp this a bit
faster then.
Thank you,
Maxim.
--
Cheers,
Maxim Veksler
"Free as in Freedom" - Do u GNU ? 5 1952
"Maxim Veksler" <hq*****@gmail. comwrites:
>def make_incremento r(n):
... return lambda x: x + n
Is the same as:
def make_incremento r(n):
def inner(x):
return x + n
return inner
When you enter make_incremento r, it allocates a memory slot (normally
we'd think of this as a stack slot since it's a function argument, but
it's really in the heap) and copies its argument there. Then you
create the function "inner" which refers to that memory slot because
of the reference to "n". Then make_incremento r returns, but since the
returned object still contains the reference to that memory slot, the
memory slot is not freed (this is the part where it becomes important
that the slot is really not on the stack). So when you call the
returned function, it still can get at that slot.
This style is very common in Scheme programming so you might read a
Scheme book if you want to understand it. The classic: http://mitpress.mit.edu/sicp/
Could some please try (if even possible) to implement the above code
without using "lambda" I believe it would help me grasp this a bit
faster then.
Does the above help?
Maxim Veksler a écrit :
Hello,
I'm new on this list and in python.
Welcome on board...
It seems python has some interesting concept of "ad hoc" function
which I'm trying to understand without much success.
Take the following code for example:
"""
>>>def make_incremento r(n):
... return lambda x: x + n
...
>>>f = make_incremento r(42) f(0)
42
>>>f(1)
43
"""
I really don't understand whats going on here.
On the first instantiating of the object "f" where does "x" gets it's
value?
Nowhere. The above code is strictly equivalent to:
def make_incremento r(n):
def inc(x):
return x + n
return inc
It's based on the fact that (for short):
1/ Python functions are first-class objects, and as such can be passed
around just like any other object
2/ Python functions are closures, meaning they carry the environment in
which they where defined.
IOW, make_incremento r(n) creates and returns a new function each time
it's called. This function remembers the value of n with which it was
created, and just awaits to be called with the missing x arg.
Or is it evaluated as 0? ie "x: 0 + 42"
>
And what is the "f" object? An integer? a pointer? an Object?
an object, instance of class function.
I'm coming from the C world...
Could some please try (if even possible) to implement the above code
without using "lambda" I believe it would help me grasp this a bit
faster then.
cf above.
FWIW, lambda is just a syntactic sugar for creating anonymous,
dead-simple functions, usually used as callbacks for generic functions
or methods like map, filter, list.sort etc.
FWIW(2), this programming style (anonymous functions, closures etc)
comes from functional programming (Haskell, ML, lisp, etc...).
Thank you,
HTH
Maxim Veksler wrote:
And what is the "f" object? An integer? a pointer? an Object?
A function.
--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/CSS/Javascript/SQL/Perl/PHP/Python*/Apache/Linux
* = I'm getting there!
Wow,
Thank you everyone for the help. I am amazed by the motivation people
have on this list to help new comers. I hope that I will be able to
contribute equally some day.
On 05 Feb 2007 14:22:05 -0800, Paul Rubin
<"http://phr.cx"@nospam. invalidwrote:
"Maxim Veksler" <hq*****@gmail. comwrites:
>>def make_incremento r(n):
... return lambda x: x + n
Is the same as:
def make_incremento r(n):
def inner(x):
return x + n
return inner
When you enter make_incremento r, it allocates a memory slot (normally
we'd think of this as a stack slot since it's a function argument, but
it's really in the heap) and copies its argument there. Then you
create the function "inner" which refers to that memory slot because
of the reference to "n". Then make_incremento r returns, but since the
returned object still contains the reference to that memory slot, the
memory slot is not freed (this is the part where it becomes important
that the slot is really not on the stack). So when you call the
returned function, it still can get at that slot.
Following the debugger on your code, I can identify the following stages:
def make_incremento r(n):
def inner(x):
return x + n
return inner
f = make_incremento r(10)
f(10)
f(0)
1. "def make_incremento r(n)" Create function object in memory and set
"make_increment or" to point to it.
2. "f = make_incremento r(10)" Set "f" to point to "inner(x) function".
Set n value to 10.
3. "f(10)" Call to inner(x), which will return "father" n + "local" x.
This means that "f" is not a pointer to make_incremento r but rather to
the internal (copied?) function.
This style is very common in Scheme programming so you might read a
Scheme book if you want to understand it. The classic:
http://mitpress.mit.edu/sicp/
I might just well do that.
Could some please try (if even possible) to implement the above code
without using "lambda" I believe it would help me grasp this a bit
faster then.
Does the above help?
all
Your explanation was excellent. Thank you.
-- http://mail.python.org/mailman/listinfo/python-list
--
Cheers,
Maxim Veksler
"Free as in Freedom" - Do u GNU ?
This means that "f" is not a pointer to make_incremento r but rather to
the internal (copied?) function.
"returned" function isthe right here. As any returned object from a function.
>
This style is very common in Scheme programming so you might read a
Scheme book if you want to understand it. The classic: http://mitpress.mit.edu/sicp/
I might just well do that.
A nice read indeed, but understand this concept first: http://en.wikipedia.org/wiki/First-class_function
--
EduardoOPadoan (eopadoan->altavix::com )
Bookmarks: http://del.icio.us/edcrypt
Blog: http://edcrypt.blogspot.com
Jabber: edcrypt at jabber dot org
ICQ: 161480283
GTalk: eduardo dot padoan at gmail dot com
MSN: eopadoan at altavix dot com This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Ian McMeans |
last post by:
I was bitten by a bug today that depended on how lambda works. It took
me quite a while to realize what was going on.
First, I made multiple lambda functions inside a loop, each of which
depended on the current loop variable.
>>> a =
>>> for index in range(5):
a.append(lambda: index)
|
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: Charlie Taylor |
last post by:
I find that I use lambda functions mainly for callbacks to things like
integration or root finding routines as follows.
flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd)
root = findRoot(xBeg, xEnd,
lambda x: y2+ lp*(x-x2) -wallFunc( x ), tolerance=1.0E-15)
I have tried using named functions instead of using lambda functions,
however, I always end up with a convoluted, hard to follow mess.
|
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: Max Rybinsky |
last post by:
Hello!
Please take a look at the example.
>>> a = # Just a list of tuples
>>> a
Now i want to get a list of functions x*y/n, for each (x, y) in a:
| |
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
|
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: Octal |
last post by:
How does the lambda library actually works. How does it know how to
evaluate _1, how does it recognize _1 as a placeholder, how does it
then calculate _1+_2, or _1+2 etc. The source files seem a bit
complicated so any explanation would be appreciated.
Thanks
|
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: ssecorp |
last post by:
I am never redefining the or reassigning the list when using validate
but since it spits the modified list back out that somehow means that
the modified list is part of the environment and not the old one.
i thought what happend inside a function stays inside a function
meaning what comes out is independent of what comes in.
Meaning if I want the list I send as a parameter to the function I
have to do x = func(x) and not just func(x) and x...
|
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...
| |
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,...
|
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: 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: 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();...
|
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: 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
|
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...
| |