473,761 Members | 5,848 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python equivalent of call/cc?

Yesterday, I was hacking around a bit, trying to figure out how to
implement the semantics of call/cc in Python. Specifically, I wanted to
translate this Scheme code to equivalent Python:

####

(define theContinuation #f)

(define (test)
(let ((i 0))
(call/cc (lambda (k) (set! theContinuation k)))
(set! i (+ i 1))
i))

(test)
(theContinuatio n)
(theContinuatio n)

####

Incidentally, those last three lines evaluate to 1, 2, and 3,
respectively.

The best Python translation I could come up with was something like this
(targeted at Python 2.5):

####
import inspect

theContinuation = None

def call_cc (f):
f (inspect.curren tframe().f_back )

def invoke (c):
exec c.f_code in c.f_globals, c.f_locals

def test():
i = 0
call_cc (lambda k: globals().updat e({'theContinua tion' : k }))
i = i + 1
print i

test()
invoke (theContinuatio n)
invoke (theContinuatio n)

####

Now, this code is wrong on a number of levels [I am indeed aware of
exactly how ugly that lambda is...], but, in particular, my
continuations / stack frames don't seem to be resuming at the right
point. I'd expect invoke (theContinuatio n) to restart on the line
immediately following call_cc, but it does not. Not surprisingly, the
output is also wrong. (I get 1, 1, and 1 rather than 1, 2, and 3.)

Can anyone help me by, perhaps pointing out some silly error I made?
Failing that, can someone show me a working implementation of call/cc
(preferably based on some form of stack inspection)?

Thanks!
--
code.py: A blog about life, the universe, and Python

http://pythonista.wordpress.com
** Posted from http://www.teranews.com **
Jul 9 '08 #1
2 2895
The Pythonista wrote:
Yesterday, I was hacking around a bit, trying to figure out how to
implement the semantics of call/cc in Python. Specifically, I wanted to
translate this Scheme code to equivalent Python:

####

(define theContinuation #f)

(define (test)
(let ((i 0))
(call/cc (lambda (k) (set! theContinuation k)))
(set! i (+ i 1))
i))

(test)
(theContinuatio n)
(theContinuatio n)

####

Incidentally, those last three lines evaluate to 1, 2, and 3,
respectively.

The best Python translation I could come up with was something like this
(targeted at Python 2.5):

####
import inspect

theContinuation = None

def call_cc (f):
f (inspect.curren tframe().f_back )

def invoke (c):
exec c.f_code in c.f_globals, c.f_locals

def test():
i = 0
call_cc (lambda k: globals().updat e({'theContinua tion' : k }))
i = i + 1
print i

test()
invoke (theContinuatio n)
invoke (theContinuatio n)

####

Now, this code is wrong on a number of levels [I am indeed aware of
exactly how ugly that lambda is...], but, in particular, my
continuations / stack frames don't seem to be resuming at the right
point. I'd expect invoke (theContinuatio n) to restart on the line
immediately following call_cc, but it does not. Not surprisingly, the
output is also wrong. (I get 1, 1, and 1 rather than 1, 2, and 3.)

Can anyone help me by, perhaps pointing out some silly error I made?
Failing that, can someone show me a working implementation of call/cc
(preferably based on some form of stack inspection)?

Thanks!
While I know absolutely no scheme what you show here is a generator in Python.

def theContinuation ():
n = 0
while 1:
n += 1
yield n
invoke = theContinuation ()

print
print invoke.next()
print invoke.next()
print invoke.next()

Maybe that is what you are looking for?

-Larry
Jul 10 '08 #2
In article <be************ ******@news.ter anews.com>,
The Pythonista <no**@this.time wrote:
>
Yesterday, I was hacking around a bit, trying to figure out how to
implement the semantics of call/cc in Python. Specifically, I wanted to
translate this Scheme code to equivalent Python:

####

(define theContinuation #f)

(define (test)
(let ((i 0))
(call/cc (lambda (k) (set! theContinuation k)))
(set! i (+ i 1))
i))

(test)
(theContinuatio n)
(theContinuatio n)
Python relies on mutables to do this:

class holder: pass

def call():
x = holder()
x.counter = 0
def cc():
x.counter += 1
return x.counter
return cc

foo = call()

print foo()
print foo()
print foo()
--
Aahz (aa**@pythoncra ft.com) <* http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
Jul 10 '08 #3

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

Similar topics

54
6574
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO FRICKIN' COOL!!! ***MAN*** that would save me a buttload of work and make my life sooooo much easier!" As opposed to minor differences of this feature here, that feature there. Variations on style are of no interest to me. I'm coming at this from a...
699
34110
by: mike420 | last post by:
I think everyone who used Python will agree that its syntax is the best thing going for it. It is very readable and easy for everyone to learn. But, Python does not a have very good macro capabilities, unfortunately. I'd like to know if it may be possible to add a powerful macro system to Python, while keeping its amazing syntax, and if it could be possible to add Pythonistic syntax to Lisp or Scheme, while keeping all of the...
14
2860
by: David MacQuigg | last post by:
I am starting a new thread so we can avoid some of the non-productive argument following my earlier post "What is good about Prothon". At Mr. Hahn's request, I will avoid using the name "Prothon" in the subject of any post to this newsgroup. Please ignore the old thread. I've also updated my webpage http://ece.arizona.edu/~edatools/Python Anyone with some good ideas for "Python 3" is welcome to contribute. I hope GvR won't sue me for...
3
2525
by: David MacQuigg | last post by:
I am writing a chapter for teaching OOP in Python. This chapter is intended as a brief introduction to replace the more complete discussion in Learning Python, 2nd ed, pp. 295-390. I need to explain instance variables. What I'm looking for is the best compromise between brevity and a full explanation. The students are non-CIS technical professionals ( engineers and scientists ). At the point they need this explanation, they have...
20
4072
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort” method. For example: li=;
28
4330
by: liorm | last post by:
Hi everyone, I need to write a web app, that will support millions of user accounts, template-based user pages and files upload. The client is going to be written in Flash. I wondered if I coudl get your opinions - what do you think is the best language to use for the server? Python or Java? And I'm talking scalability, object oriented, development tools etc. Thansk for any idea! I'd love to hear it Happy New 2006,
26
3247
by: Christoph Zwerschke | last post by:
You will often hear that for reasons of fault minimization, you should use a programming language with strict typing: http://turing.une.edu.au/~comp284/Lectures/Lecture_18/lecture/node1.html I just came across a funny example in which the opposite is the case. The following is a binary search algorithm in Java. It searches a value in an ordered array a of ints: public static int binarySearch(int a, int key) {
26
2727
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
10
1410
by: Mladen Gogala | last post by:
I am a Python newbie who decided to see what that Python fuss is all about. Quite frankly, I am a bit perplexed. After having had few months of experience with Perl (started in 1994 with Perl v4, and doing it ever since) , here is what perplexes me: perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' The equivalent in Python looks like this: Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51)
0
9522
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9336
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
10111
Oralloy
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...
0
9948
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
9902
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
9765
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
6603
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
3866
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
3
2738
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.