[Python-Dev] Re: switch statement
Shannon -jj Behrens
jjinux at gmail.com
Thu Apr 21 23:10:14 CEST 2005
On 4/21/05, Michael Hudson <mwh at python.net> 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?
Sure.
Now that I'm actually trying to come up with an example, I'm noticing
that Ocaml is very different than Python because Python distinguishes
statements and expressions, unlike say, Scheme. Furthermore, it's
important to minimize the number of new keywords and avoid excessive
punctuation (which Ocaml is full of). Hence, I propose something
like:
def handle_token(token):
match token:
NUMBER:
return number / a
WHITESPACE if token.value == "\n":
return NEWLINE
(a, b):
return a / b
else:
return token
Hence, the syntax is something like (in pseudo EBNF):
'match' expr ':'
{match_expression ':'
block}*
'else' ':'
block
match_expr ::= lvalue | constant_expression
Sematically, the above example translates into:
def handle_token(token):
if token == NUMBER:
return number / a
elif token == WHITESPACE and token.value == "\n":
return NEWLINE
elif "setting (a, b) = token succeeds":
return a / b
else:
return token
However, unlike the code above, you can more easily and more
aggressively optimize.
Best Regards,
-jj
--
I have decided to switch to Gmail, but messages to my Yahoo account will
still get through.
More information about the Python-Dev
mailing list