binding a reference to a variable

Andrew Koenig ark at research.att.com
Wed Apr 10 11:42:43 EDT 2002


>> I want to be able to stuff an object into a larger data
>> structure and have that object reach out into a variable and leave a
>> trail of breadcrumbs.

Michael> Can you come up with a more fleshed out example?  There
Michael> probably are some ways of doing what you want but they will
Michael> be hackish and fragile (grovelling around in frame objects,
Michael> etc).  OTOH, if you explain what you are trying to acheive,
Michael> perhaps we can come up with a more elegant way (it strikes me
Michael> that 2.2's properties may help here, for instance).

Sure.  I'm thinking about how to implement Snobol-style pattern
matching in Python.  I know that someone has done it before, but
I want to approach it from a completely different direction.

Snobol lets you write stuff like this:

        name ? pos(0) (break('@') . id) '@' (rpos(0) . domain)

(Experienced Snobol programmers will note that I have deliberately
introduced some extra parentheses and an '?' operator for clarity)

Here, "pos" denotes an offset from the beginning of a string,
"rpos" denotes an offset from the end, and break(s) matches the
string from the present position up to and not including the first
character that occurs anywhere in s.

The point of this example is the . operator, which takes a pattern
(by value) as its left argument and a variable (by reference) as its
right argument.  The result is a pattern that matches the same strings
as the left argument, but if the match is successful, it assigns
the substring matched to the variable that is the right argument.

As it happens, I can implement much the same idea in C++, though
the exact details of operator overloading make it look somewhat
different:

    string id, domain;
    match(name, pos(0) + (break("@") >> id) + "@" + (rpos(0) >> domain));

and I can also implement a similar idea in ML, though I don't
think it's worth going into details here.

So I was thinking about how I would do something similar in Python.

Focusing just on the  (break("@") . id)  subexpression, how would
one implement it?  That's what led me on this path.

Michael> Having random variables change their values at random times
Michael> strikes me as an idea that might come from - ooh - C++?
Michael> <wink>

Well, in this case, the idea came from Snobol, vintage 1968 or so.

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark



More information about the Python-list mailing list