What can you do in LISP that you can't do in Python

mikel evins himself at mikelevins.com
Thu May 24 09:58:21 CEST 2001


I don't know the answer to the question in the subject line. I'm a fan of
both LISP and Python, considerably more experienced in LISP than in Python
(but I've written nontrivial programs in both). But as a fun intellectual
exercise I thought I'd try to think of a typically LISPy kind of thing that
I don't know how to do in Python, and see whether someone who knows Python
better does know how to do it.

Here's the Common Lisp code:

(let* ((count 0)
       (incrementer #'(lambda () (setq count (1+ count)))))
  (defmacro counting-setq (var val)
    `(progn
       (funcall ,incrementer)
       (setq ,var ,val)
       ,count)))

What it does is this: it defines a new version of SETQ called
'counting-setq'. This new operation does the same thing that SETQ does: it
sets the value of a variable. But it does something else, too: it counts how
many times you call it and saves the current count in a variable that nobody
but counting-setq can see or affect. When it sets a variable it increments
the current count and then returns it.

Obviously, this is kind of a trivial piece of code, but it illustrates a
couple of interesting things about LISP:

You can create new syntax for the language by defining macros. Macros are
forms that expand into other forms before being evaluated, so if there is
some syntactic feature that you really wish the language had that it
doesn't, you can make it from within the language.

You can create a lexical environment and define functions that operate
within that lexical environment. The variables in there are accessible to
the functions that you create in the environment, but nowhere else. To the
functions defined in the environment the variables may as well be globals,
but to any other function they are completely invisible and inaccessible. So
you can have 'global' state that is nevertheless safe from diddling by
anybody who isn't supposed to see it. counting-setq carries its count
variable around with it wherever it goes, but nobody else can mess with it.

I don't know how to do this exact thing in Python; does someone else?







More information about the Python-list mailing list