[Python-Dev] re: PEP 275: Switching on Multiple Values, Rev 1.2

M.-A. Lemburg mal@lemburg.com
Mon, 26 Nov 2001 11:06:33 +0100


Brian Slesinsky wrote:
> 
> Hi,
> 
> I'm new to the list and apologies for going off-topic a bit (this has
> nothing to do with performance):
> 
> If Python implements switch statements it would be a shame not to have
> pattern-matching in switch statements too.  This is a feature that has
> long been used in functional languages like ML.  For example, here's
> pattern matching on a tuple:
> 
> def foo(a,b):
>   switch (f(a), g(b)):
>     case (c,1): something(c)  # if g(b)==1, assigns c = f(a)
>     case (1,d): something(d)  # if f(a)==1, assigns d = g(b)
>     case (c,_): something(c)  # any tuple: assigns c = f(a), _ is wildcard
> 
> Some syntactic sugar related to this would be a way to pattern-match on
> arbitrary objects as is now done with tuples:
> 
> def foo(pair, number):
>   Pair(x,y) = pair  # assert isinstance(pair,Pair), assigns x and y
>   int(i) = number   # assert type(x)==IntType, assign i
> 
> (To implement this, classes would have a __tuple__ method that returns the
> tuple for matching.  By convention it should return the arguments to its
> __init__ method.)
> 
> Note how type-checking happens in a very natural way:
>   a = int(a)  # convert a
>   int(a) = a  # type-check a
> 
> Combining the two:
> 
> def sum(pairOrInt):
>   switch pairOrInt:
>     case int(a): return a
>     case Pair(x,y): return sum(x)+sum(y)
> 
> Here's some documentation on how it's done in Cyclone, a C variant from
> AT&T that seems to have a strong ML influence:
> 
> http://www.research.att.com/projects/cyclone/online-manual/main-screen005.html

Note that the switch implementations proposed in the PEP both
use Python dictionaries as basis for the jump location lookup.
The aim is speed up switches on constants which currently are
linear in number of cases.

I'm not sure how your proposal fits in here, but it looks like
the current if-elif-else syntax is better suited to it than
some trying to use a switch-dictionary with some special objects
to implement wild-card matching, e.g.

if type(pairOrInt) == type(1):
   return pairOrInt
elif type(pairOrInt) == type(()) and len(pairOrInt) == 2:
   x,y = pairOrInt
   return sum(x) + sum(y)

-- 
Marc-Andre Lemburg
CEO eGenix.com Software GmbH
______________________________________________________________________
Consulting & Company:                           http://www.egenix.com/
Python Software:                        http://www.lemburg.com/python/