473,804 Members | 2,034 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

iterative lambda construction

Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python. I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times. For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.

I can do it recursively, like this:

def repeated(f, count):
if count == 1:
return f
else:
return lambda x: f(repeated(f, count - 1)(x)

But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun

For the life of me, I can't figure out why. It seems like for count =
2, for example, the results from repeated2 should be lambda x: f(f(x)),
but it doesn't seem to be.

Jul 18 '05 #1
4 1634
"markscottwrigh t" <ma************ *@gmail.com> writes:
But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun

For the life of me, I can't figure out why. It seems like for count =
2, for example, the results from repeated2 should be lambda x: f(f(x)),
but it doesn't seem to be.


It's Python's scoping madness. Try:

def repeated2(f, count):
newfun = lambda x: x # identity
for i in range(count):
newfun = lambda x, g=newfun: g(f(x))
return newfun
Jul 18 '05 #2
"markscottwrigh t" <ma************ *@gmail.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python. I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times. For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.

I can do it recursively, like this:

def repeated(f, count):
if count == 1:
return f
else:
return lambda x: f(repeated(f, count - 1)(x)

But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun


The trouble is that Python's scoping rules are subtly different from
Schemes, so you're binding to the wrong instance of newfun. You should do
this:

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x, g=newfun: g(f(x))
return newfun

Alternatively, you could do it this way:

def repeated3(f, count):
def g(x):
for i in range(count):
x = f(x)
return x
return g
Jul 18 '05 #3
markscottwright wrote:
Just for the hell of it, I've been going through the old Scheme-based
textbook "Structure and Interpretation of Computer Programs" and seeing
what I can and can't do with python. I'm trying to create a function
that returns the function (not the results of the function, but a
function object) that results from applying function f to it's (single)
argument N times. For example, if you have "def sq(x): return x*x",
then repeated(sq, 2)(2) = 16, repeated(sq, 3)(2) = 256, etc.

I can do it recursively, like this:

def repeated(f, count):
if count == 1:
return f
else:
return lambda x: f(repeated(f, count - 1)(x)

But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun

For the life of me, I can't figure out why.


Your problem is that lambdas (and defs) do late-binding. Consider the
following code:

py> newfun = (1).__add__
py> id(newfun)
18354384
py> newfun = lambda: sys.stdout.writ e('%s' % id(newfun))
py> id(newfun)
18217328
py> newfun()
18217328

Note that the id of 'newfun' is the same in the body of the lambda as
the id of 'newfun' after the lambda is defined. That is, if 'newfun' in
the lambda were to be called, it would call the lambda function
recursively, instead of calling the previous 'newfun'. This is why
you're getting infinite recursion.

The reason this happens is that, when a name is not bound by the
argument list of a function, Python will look for that name in the
enclosing scopes. Since the lambda does not bind the name 'newfun',
Python looks out to the enclosing scope to find 'newfun' (which, in this
case, happens to be the funciton itself).

One solution to this problem is to bind the old function to a name in
the argument list of your lambda[1]:

py> def repeated2(f, count):
.... newfun = f
.... for i in range(count - 1):
.... def newfun(x, oldfun=newfun):
.... return oldfun(f(x))
.... return newfun
....
py> def square(x):
.... return x**2
....
py> repeated2(squar e, 2)(2)
16
py> repeated2(squar e, 3)(2)
256

Another possibility would be to store the old function as part of a
class instance:

py> class Composer(object ):
.... def __init__(self, outerfunc, innerfunc):
.... self.outerfunc = outerfunc
.... self.innerfunc = innerfunc
.... def __call__(self, x):
.... return self.outerfunc( self.innerfunc( x))
....
py> def repeated2(f, count):
.... newfun = f
.... for _ in range(count - 1):
.... newfun = Composer(newfun , f)
.... return newfun
....
py> repeated2(squar e, 2)(2)
16
py> repeated2(squar e, 3)(2)
256

Note that either way, you need some means to store the old value of
newfunc. In the first case, it's stored by binding it as a default
value of one of the the function's arguments. In the second case, it's
stored as an instance attribute of a class.

STeVe

[1] I use def instead of lambda. See "Inappropri ate use of Lambda" in
http://www.python.org/moin/DubiousPython
Jul 18 '05 #4
On Mon, Feb 21, 2005 at 01:14:00PM -0800, Paul Rubin wrote:
"markscottwrigh t" <ma************ *@gmail.com> writes:
But when I try to do it iteratively, it just hangs when I try to
evaluate the results (for count > 1):

def repeated2(f, count):
newfun = f
for i in range(count-1):
newfun = lambda x: newfun(f(x))
return newfun

For the life of me, I can't figure out why. It seems like for count =
2, for example, the results from repeated2 should be lambda x: f(f(x)),
but it doesn't seem to be.


It's Python's scoping madness. Try:

def repeated2(f, count):
newfun = lambda x: x # identity
for i in range(count):
newfun = lambda x, g=newfun: g(f(x))
return newfun


Ahh, but not sufficienty evil or pernicious.

def evil(f, count):
def apply_evil(accu m, func):
return func(accum)
def pernicious(x):
return reduce(apply_ev il, [f]*count, x)
return pernicious

def f(x):
return x+x

print evil(f, 3)(2)

More seriously I'd go without the recursion and just make a wrapper
that applies the function count times in a wrapper.

def benign(f, count):
def wrap(x):
result = f(x)
for (i) in range(count-1):
result = f(result)
return result
return wrap

print benign(f, 3)(2)

-Jack
Jul 18 '05 #5

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

Similar topics

53
3708
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
3428
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
3510
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...
3
1427
by: wakun | last post by:
Hi there, I am working a project in numerical computation in which iterative method is applied for solving equation. The problem is so big and slow. Few days ago, I found a paper on metaprogramming , it seems that such technique has good performance for some case. For ordinary case, my code for implementing iterative method like for (int i=1; i<N; i++) { x = f(x, x);
267
10869
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
23
5340
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...
5
2165
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
11
1391
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...
1
2633
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
9711
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
9591
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
10343
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
10331
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
10087
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
9166
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
7631
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
6861
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();...
1
4306
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 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.