Deferred Evaluation in Recursive Expressions?

Diez B. Roggisch deets at nospam.web.de
Tue May 9 09:16:45 EDT 2006


birchb at ozemail.com.au wrote:

> While working on type expressions I am rather stuck for a
> way to express recursive types.  A simple example of this is a
> singly-linked list of integers. In some languages you have compiler
> syntax
> which suspends evaluation so you can have recursive types. e.g.
> 
>    typedef Linked_List := int, Linked_List
> 
> In LISP I would use a macro.
> 
> I have tried using classes:
> 
>    class Linked_List(object):
>          typedef = (int, Linked_List)
> 
> The closest I have got in Python is the following:
> 
>    Linked_List = (int, lambda: Linked_List)      # linked list of int
> 
> this is OK, because lambda makes closure which is not executed. However
> it required the user of the type expression to call any lfunctions
> found whilst traversing the tree.
> 
> To make this a little more OO, I could use a constructor to wrap the
> function:
> 
>    Linked_List = (int, recursive(lambda: Linked_List))      # linked
> list of int
> 
> but I am not satisfied with the "look".
> 
> Any suggestions?

If you are after lazy evaluation: no - there is no chance python will grow
that (Well, maybe there is some PEP out there - but if, it weould be for
Py3K)

The natural approach for your actual example though would be a generator.
Which, when used in for .. in .. even looks natural to the eye:

def squares():
    c =  1
    while True:
      yield c ** 2

for n in squares():
    ... # do something fancy


Diez



More information about the Python-list mailing list