[Python-Dev] Re: switch statement

Samuele Pedroni pedronis at strakt.com
Thu Apr 21 16:02:38 CEST 2005


Michael Hudson wrote:

>Shannon -jj Behrens <jjinux at gmail.com> writes:
>
>  
>
>>On 4/20/05, M.-A. Lemburg <mal at egenix.com> wrote:
>>
>>    
>>
>>>My use case for switch is that of a parser switching on tokens.
>>>
>>>mxTextTools applications would greatly benefit from being able
>>>to branch on tokens quickly. Currently, there's only callbacks,
>>>dict-to-method branching or long if-elif-elif-...-elif-else.
>>>      
>>>
>>I think "match" from Ocaml would be a much nicer addition to Python
>>than "switch" from C.
>>    
>>
>
>Can you post a quick summary of how you think this would work?
>
>  
>
Well, Python lists are used more imperatively and are not made up with 
cons cells,
we have dictionaries which because of ordering issues are not trivial to 
match,
 and  no general ordered records with labels. We have objects and not 
algebraic
data types. Literature on the topic usually indicates the visitor 
pattern as the
moral equivalent of pattern matching in an OO-context vs. algebraic data 
types/functional
one. I agree with that point of view and Python has idioms for the 
visitor pattern.

Interestingly even in the context of objects one can leverage the 
infrastructure that is
there for generalized copying/pickling to allow generalized pattern 
matching of
nested object data structures. Whether it is practical I don't know.

 >>> class Pt:
...   def __init__(self, x,y):
...     self.x = x
...     self.y = y
...
 >>> p(lambda _: Pt(1, _()) ).match(Pt(1,3))
(3,)
 >>> p(lambda _: Pt(1, Pt(_(),_()))).match(Pt(1,Pt(Pt(5,6),3)))
(<__main__.Pt instance at 0x40200b4c>, 3)

http://codespeak.net/svn/user/pedronis/match.py is an experiment in that 
direction (preceding this discussion
and inspired while reading a book that was using OCaml for its examples).

Notice that this is quite grossly subclassing pickling infrastracture  
(the innocent bystander should probably not try that), a cleaner 
approach redoing that logic with matching in mind is possible and would 
be preferable.













More information about the Python-Dev mailing list