[Python-Dev] Re: switch statement
Andrew McGregor
andrew at indranet.co.nz
Thu Apr 21 12:36:56 CEST 2005
I can post an alternative, inspired by this bit of Haskell (I've
deliberately left out the Haskell type annotation for this):
zoneOpts argv =
case getOpt Permute options argv of
(o,n,[]) -> return (o,n)
(_,_,errs) -> error errs
which could, in a future Python, look something like:
def zoneOpts(argv):
case i of getopt(argv, options, longoptions):
i[2]:
raise OptionError(i[2])
True:
return i[:2]
The intent is that within the case, the bit before each : is a boolean
expression, they're evaluated in order, and the following block is
executed for the first one that evaluates to be True. I know we have
exceptions for this specific example, but it's just an example. I'm
also assuming for the time being that getopt returns a 3-tuple
(options, arguments, errors) like the Haskell version does, just for
the sake of argument, and there's an OptionError constructor that will
do something with that error list..
Yes, that is very different semantics from a Haskell case expression,
but it kind of looks like a related idea. A more closely related idea
would be to borrow the Haskell patterns:
def zoneOpts(argv):
case getopt(argv, options, longoptions):
(o,n,[]):
return o,n
(_,_,errs):
raise OptionError(errs)
where _ matches anything, a presently unbound name is bound for the
following block by mentioning it, a bound name would match whatever
value it referred to, and a literal matches only itself. The first
matching block gets executed.
Come to think of it, it should be possible to do both.
Not knowing Ocaml, I'd have to presume that 'match' is somewhat similar.
Andrew
On 21/04/2005, at 9:30 PM, 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?
>
> Cheers,
> mwh
>
> --
> We did requirements and task analysis, iterative design, and user
> testing. You'd almost think programming languages were an interface
> between people and computers. -- Steven Pemberton
> (one of the designers of Python's direct ancestor ABC)
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
> http://mail.python.org/mailman/options/python-dev/
> andrew%40indranet.co.nz
>
>
More information about the Python-Dev
mailing list