Here's my implementation, using tuples. But bear in mind that for almost everything Python's used for, Python lists (i.e. vectors) are good enough.
def cons(x, y):
return (x, y)
def car(x):
return x if x == () else x[0]
def cdr(x):
return x if x == () else x[1]
def append(x, y):
return y if x == () else cons(car(x), append(cdr(x), y))
def rev(x, y):
return y if x == () else rev(cdr(x), cons(car(x), y))
def reverse(x):
return rev(x, ())
def null(x):
return x == ()
def list(*tuple):
if len(tuple) < 1:
return ()
else:
x = ()
for i in reversed(range(len(tuple))):
x = cons(tuple[i], x)
return x
def mapcar(fn, x):
return () if x == () else cons(apply(fn, (car(x),)), mapcar(fn, cdr(x)))
----------------------
>>> import sexpr
>>> print sexpr.cons(1, 2)
(1, 2)
>>> x = sexpr.list(1, 2, 3, 4)
>>> print x
(1, (2, (3, (4, ()))))
>>> print sexpr.reverse(x)
(4, (3, (2, (1, ()))))
>>> print x
(1, (2, (3, (4, ()))))
>>> print sexpr.append(x, sexpr.cdr(sexpr.reverse(x)))
(1, (2, (3, (4, (3, (2, (1, ())))))))
>>> print sexpr.mapcar(lambda y : y ∗ y, x)
(1, (4, (9, (16, ()))))