Re: Can't take the tail of a list without copying via List[1:]?

Aaron Watters (aaron@funcity.njit.edu)
Mon, 8 Aug 1994 15:46:25 GMT

In article <199408080345.AA22586@elvis.med.Virginia.EDU> "Steven D. Majewski" <sdm7g@elvis.med.virginia.edu> writes:
>On Aug 5, 13:14, Aaron Watters wrote:
>>
>> Summary: Can I or why can't I take the cdr of a list without
>> copying the entire top level structure of the list?....

For those that are following the thread I thought I'd
resolve it.

Summary: For read-only access there's little problem
in implementing lisp-like lists over python lists using
a wrapper class. For construction or modification,
there are simple things that lisp-lists can do that python
lists can't -- but you can reimplement lisp-lists or
rethink your design most of the time.

A wrapper for read only access using lisp-like list traversal:
===
# implementing lisp like list access in python
# except:
# no recursive construction, only retrieval...

# instead of directly accessing lists use a wrapper class
# that points into the list...

class ListPtr:
def __init__(self,List=[],position=0):
self.TheList=List
self.TheIndex=position

def first(self):
return self.TheList[self.TheIndex]

def nth(self,offset):
return self.TheList[self.TheIndex + offset - 1]

def rest(self):
return ListPtr(self.TheList, self.TheIndex+1)
===
In this case my example can be done as follows
(assuming the subroutines don't try to modify the
top level structure of the list).
===
def NeatStuff(ListP):
Head, Tail=ListP.first(), ListP.rest()
if Head==1:
return Groovystuff(Tail)
elif Head==2:
return Nastystuff(Tail)
else:
return Neatstuff(Tail)
===

Now, the following cannot be done using built-in python lists:
(setq x ("This" 'dummy))
(setf (rest x) x)
which creates the cyclic list x=("This" "This" "This" "This" ...)
You also cannot create lists that share, for example, a common
tail (without copying the tail):
(setq tail (2 4))
(setq mults-of-2 `(0 . ,tail))
(setq powers-of-2 `(1 , ,tail))

If you really want to do the above you can reimplement lisp-style
lists as a python class, and even use the neat special methods for
easy construction and printing syntax if you're clever.
[I actually did this as my first python experiment that wasn't
completely trivial.]

As someone pointed out, however, the kinds of stuff that lisp
hackers frequently do with lists would probably be better implemented using
classes, so maybe a better approach is to think in python rather
than make python look like (old style) lisp, if possible.
Aaron Watters
Department of Computer and Information Sciences
New Jersey Institute of Technology
University Heights
Newark, NJ 07102
phone (201)596-2666
fax (201)596-5777
home phone (908)545-3367
email: aaron@vienna.njit.edu