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

Brian Slesinsky bslesins@best.com
Fri, 23 Nov 2001 17:12:23 -0800 (PST)


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

----------------------------------------------------------------------
Brian Slesinsky