[plt-scheme] guido on tail recursion

From: Nadeem Abdul Hamid (nadeem at acm.org)
Date: Fri Apr 24 16:55:55 EDT 2009

Hmm... I see what you mean about the TCO. In Python, one could write:

def readline(func):
     '''readline : (string -> a) -> a'''
     func(raw_input())

def loop():
     def callback(line):
         print "you said %s" % line
         loop()
     print "Say something"
     readline(callback)

And it definitely doesn't optimize because if you type EOF at some  
point you get a big long stack trace... talk about turtles all the way  
down!

However, the natural imperative way to test such a readline in Python  
would seem to me to be something like:

def imp_loop():
     while True:
         print "Say something"
         readline(lambda line: void_print("you said %s" % line))

No?

--- nadeem




On Apr 24, 2009, at 4:31 PM, Eli Barzilay wrote:

> Yes.  I should also have added that control might go through several
> pieces of code, and most such pieces of code will do the "obvious
> thing" and end with tail calls -- so things just sort themselves out.
> (I remember that Joe Marshall phrased this nicely at some point, I
> don't remember the sentence though.)
>
>
> On Apr 24, Matthias Felleisen wrote:
>>
>> I think Eli meant to add that the call to the callback is in TP and
>> that the call to loop in the callback is in TP and, by the TCO
>> guarantee for Scheme, all of this (well-designed) code becomes a loop
>> (from the perspective of space consumption) on the target machine --
>> Matthias
>>
>> On Apr 24, 2009, at 3:57 PM, Eli Barzilay wrote:
>>
>>> Here's a piece of code that I'm using now -- it's some gui thing,  
>>> and
>>> for technical reasons, I'm implementing a `read-line' method that
>>> reads a line from the gui somehow.  Since the gui is on a single
>>> thread, I made `read-line' get a callback, which is called on the  
>>> line
>>> when it has been read.  To play with my code I wrote a loop that  
>>> reads
>>> lines in a loop:
>>>
>>>         (let loop ()
>>>           (output "Say something")
>>>           (read-line (lambda (line)
>>>                        (output (format "You said: ~a" line))
>>>                        (loop))))
>>>
>>> The thing is that the loop goes through the callback, so it doesn't
>>> translate to a simple (imperative) loop.  Is there a way to do  
>>> this in
>>> python?
>>>
>>> (Looks like it shouldn't be hard, but I can't think of anything.  It
>>> might be that I'm blinded by scheme, or it might be the result of
>>> sleep deprivation...)
>
> -- 
>          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli  
> Barzilay:
>                  http://www.barzilay.org/                 Maze is  
> Life!
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.