Re: [Python-Dev] Re: switch statement
On 4/28/05, Stephen J. Turnbull <[EMAIL PROTECTED]> wrote: > > "Guido" == Guido van Rossum <[EMAIL PROTECTED]> writes: > > Guido> You mean like this? > > if x > 0: > ...normal case... > elif y > 0: > abnormal case... > else: > ...edge case... > > The salient example! If it's no accident that those conditions are > mutually exclusive and exhaustive, doesn't that code require at least > a comment saying so, and maybe even an assertion to that effect? I usually do: if ...: return ... if ...: return ... assert ... return ... Michael ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
> Exaggeration in defense of elegance is no vice. Maybe not, but it still sounds like BS to me. -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
> "Guido" == Guido van Rossum <[EMAIL PROTECTED]> writes: Guido> You mean like this? if x > 0: ...normal case... elif y > 0: abnormal case... else: ...edge case... The salient example! If it's no accident that those conditions are mutually exclusive and exhaustive, doesn't that code require at least a comment saying so, and maybe even an assertion to that effect? Where you can use a switch, it gives both, and throws in economy in both source and object code as a bonus. Not a compelling argument---your example shows switches are not universally applicable---but it's a pretty good deal. Guido> You have guts to call that bad style! :-) Exaggeration in defense of elegance is no vice. -- School of Systems and Information Engineering http://turnbull.sk.tsukuba.ac.jp University of TsukubaTennodai 1-1-1 Tsukuba 305-8573 JAPAN Ask not how you can "do" free software business; ask what your business can "do for" free software. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Michael Chermside wrote: > if x == 1:|if condition_1: > do_1() |y = 1 > elif x == 2: |elif condition_2: > do_2() |y = 2 > elif x == 3: |elif condition_3: > do_3() |y = 3 > else: |else: > default() |y = 4 This inspired a twisted thought: if you just redefine truth, you don't have to repeat the variable. <0.9 wink> True = x if 1: do_1() elif 2: do_2() elif 3: do_3() else: default() Shane ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] Re: switch statement
Guido writes: > You mean like this? > > if x > 0: >...normal case... > elif y > 0: > abnormal case... > else: > ...edge case... > > You have guts to call that bad style! :-) Well, maybe, but this: if x == 1: do_number_1() elif x == 2: do_number_2() elif x == 3: do_number_3() elif y == 4: do_number_4() elif x == 5: do_number_5() else: raise ValueError is clearly bad style. (Even knowing what I did here, how long does it take you to find the problem? Hint: line 7.) I've seen Jim's recipe in the cookbook, and as I said there, I'm impressed by the clever implementation, but I think it's unwise. PEP 275 proposes an O(1) solution... either by compiler optimization of certain if-elif-else structures, or via a new syntax with 'switch' and 'case' keywords. (I prefer the keywords version myself... that optimization seems awefully messy, and wouldn't help with the problem above.) Jim's recipe fixes the problem given above, but it's a O(n) solution, and to me the words 'switch' and 'case' just *scream* "O(1)". But perhaps it's worthwhile, just because it avoids repeating "x ==". Really, this seems like a direct analog of another frequently-heard Python gripe: the lack of a conditional expression. After all, the problems with these two code snippets: if x == 1:|if condition_1: do_1() |y = 1 elif x == 2: |elif condition_2: do_2() |y = 2 elif x == 3: |elif condition_3: do_3() |y = 3 else: |else: default() |y = 4 is the repetition of "x ==" and of "y =". As my earlier example demonstrates, a structure like this in which the "x ==" or the "y =" VARIES has a totally different *meaning* to the programmer than one in which the "x ==" or "y =" is the same for every single branch. But let's not start discussing conditional expressions now, because there's already more traffic on the list than I can read. -- Michael Chermside ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
> Greg> 1) Repeating the name of the thing being switched on all the > Greg> time, and the operator being used for comparison. > > What's worse, to my mind, is the not infrequent case where the thing > being switched on or the operator changes. Sure, that's bad style, > but sometimes you have to read other people's code like that. You mean like this? if x > 0: ...normal case... elif y > 0: abnormal case... else: ...edge case... You have guts to call that bad style! :-) -- --Guido van Rossum (home page: http://www.python.org/~guido/) ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
> "Greg" == Greg Ewing <[EMAIL PROTECTED]> writes: Greg> Two things are mildly annoying about if-elif chains as a Greg> substitute for a switch statement: Greg> 1) Repeating the name of the thing being switched on all the Greg> time, and the operator being used for comparison. What's worse, to my mind, is the not infrequent case where the thing being switched on or the operator changes. Sure, that's bad style, but sometimes you have to read other people's code like that. -- School of Systems and Information Engineering http://turnbull.sk.tsukuba.ac.jp University of TsukubaTennodai 1-1-1 Tsukuba 305-8573 JAPAN Ask not how you can "do" free software business; ask what your business can "do for" free software. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Donovan Baarda wrote: Agreed. I don't find any switch syntaxes better than if/elif/else. Speed benefits belong in implementation optimisations, not new bad syntax. Two things are mildly annoying about if-elif chains as a substitute for a switch statement: 1) Repeating the name of the thing being switched on all the time, and the operator being used for comparison. 2) The first case is syntactically different from subsequent ones, even though semantically all the cases are equivalent. -- Greg Ewing, Computer Science Dept, +--+ University of Canterbury, | A citizen of NewZealandCorp, a | Christchurch, New Zealand | wholly-owned subsidiary of USA Inc. | [EMAIL PROTECTED] +--+ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
On Mon, 2005-04-25 at 21:21 -0400, Brian Beck wrote: > Donovan Baarda wrote: > > Agreed. I don't find any switch syntaxes better than if/elif/else. Speed > > benefits belong in implementation optimisations, not new bad syntax. > > I posted this 'switch' recipe to the Cookbook this morning, it saves > some typing over the if/elif/else construction, and people seemed to > like it. Take a look: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692 Very clever... you have shown that current python syntax is capable of almost exactly replicating a C case statement. My only problem is C case statements are ugly. A simple if/elif/else is much more understandable to me. The main benefit in C of case statements is the compiler can optimise them. This copy of a C case statement will be slower than an if/elif/else, and just as ugly :-) -- Donovan Baarda <[EMAIL PROTECTED]> http://minkirri.apana.org.au/~abo/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] Re: switch statement
Donovan Baarda wrote: > Agreed. I don't find any switch syntaxes better than if/elif/else. Speed > benefits belong in implementation optimisations, not new bad syntax. I posted this 'switch' recipe to the Cookbook this morning, it saves some typing over the if/elif/else construction, and people seemed to like it. Take a look: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692 -- Brian Beck Adventurer of the First Order ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
On Mon, 2005-04-25 at 18:20 -0400, Jim Jewett wrote: [...] > If speed for a limited number of cases is the only advantage, > then I would say it belongs in (at most) the implementation, > rather than the language spec. Agreed. I don't find any switch syntaxes better than if/elif/else. Speed benefits belong in implementation optimisations, not new bad syntax. -- Donovan Baarda <[EMAIL PROTECTED]> http://minkirri.apana.org.au/~abo/ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] Re: switch statement
M.-A. Lemburg wrote: > Having a simple switch statement > would enable writing very fast parsers in Python - ... > Instead of having one function call per token, you'd > only have a single dict lookup. > BTW, has anyone in this thread actually read the PEP 275 ? I haven't actually seen any use cases outside of parsers branching on a constant token. When I see stacked elif clauses, the condition almost always includes some computation (perhaps only ".startswith" or "in" or a regex match), and there are often cases which look at a second variable. If speed for a limited number of cases is the only advantage, then I would say it belongs in (at most) the implementation, rather than the language spec. -jJ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
On 4/25/05, M.-A. Lemburg <[EMAIL PROTECTED]> wrote: > Shannon -jj Behrens wrote: > > On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> wrote: > > > >>Fredrik Lundh wrote: > >> > >>>PS. a side effect of the for-in pattern is that I'm beginning to feel > >>>that Python > >>>might need a nice "switch" statement based on dictionary lookups, so I can > >>>replace multiple callbacks with a single loop body, without writing too > >>>many > >>>if/elif clauses. > >> > >>PEP 275 anyone ? (http://www.python.org/peps/pep-0275.html) > >> > >>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. > > PEP 275 is about branching based on dictionary lookups which > is somewhat different than pattern matching - for which we > already have lots and lots of different tools. > > The motivation behind the switch statement idea is that of > interpreting the multi-state outcome of some analysis that > you perform on data. The main benefit is avoiding Python > function calls which are very slow compared to branching to > inlined Python code. > > Having a simple switch statement > would enable writing very fast parsers in Python - > you'd let one of the existing tokenizers such as mxTextTools, > re or one of the xml libs create the token input data > and then work on the result using a switch statement. > > Instead of having one function call per token, you'd > only have a single dict lookup. > > BTW, has anyone in this thread actually read the PEP 275 ? I'll admit that I haven't because dict-based lookups aren't as interesting to me as an Ocaml-style match statement. Furthermore, the argument "Instead of having one function call per token, you'd only have a single dict lookup" isn't very compelling to me personally, because I don't have such a performance problem in my applications, which isn't to say that it isn't important or that you don't have a valid point. Best Regards, -jj -- I have decided to switch to Gmail, but messages to my Yahoo account will still get through. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Shannon -jj Behrens wrote: > On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> wrote: > >>Fredrik Lundh wrote: >> >>>PS. a side effect of the for-in pattern is that I'm beginning to feel >>>that Python >>>might need a nice "switch" statement based on dictionary lookups, so I can >>>replace multiple callbacks with a single loop body, without writing too >>>many >>>if/elif clauses. >> >>PEP 275 anyone ? (http://www.python.org/peps/pep-0275.html) >> >>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. PEP 275 is about branching based on dictionary lookups which is somewhat different than pattern matching - for which we already have lots and lots of different tools. The motivation behind the switch statement idea is that of interpreting the multi-state outcome of some analysis that you perform on data. The main benefit is avoiding Python function calls which are very slow compared to branching to inlined Python code. Having a simple switch statement would enable writing very fast parsers in Python - you'd let one of the existing tokenizers such as mxTextTools, re or one of the xml libs create the token input data and then work on the result using a switch statement. Instead of having one function call per token, you'd only have a single dict lookup. BTW, has anyone in this thread actually read the PEP 275 ? -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 25 2005) >>> Python/Zope Consulting and Support ...http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] Re: switch statement
Michael Chermside wrote: > Now the pattern matching is more interesting, but again, I'd need to > see a proposed syntax for Python before I could begin to consider it. > If I understand it properly, pattern matching in Haskell relies > primarily on Haskell's excellent typing system, which is absent in > Python. Why not just use classes? With either mixins or new-style classes, it is quite reasonable to use many small classes for fine distinctions. Change if predicate1(obj): action1(obj) elif predicate2(obj): action2(obj) ... else: default(obj) into either try: obj.action(locals()) except AttributeError: default(obj, locals()) or if hasattr(obj, "action"): obj.action(locals()) else: And then define an action method (perhaps through inheritance from a mixin) for any object that should not take the default path. The object's own methods will have access to any variables used in the match and locals will have access to the current scope. If you have at least one class per "switch", you have a switch statement. The down sides are that (1) Your domain objects will have to conform to a least a weak OO model (or take the default path) (2) Logic that should be together will be split up. Either classes will be modified externally, or the "switch statement" logic will be broken up between different classes. If single-method mixins are used to keep the logic close, then real objects will have to pick an ancestor for what may seem like arbitrary reasons. These objections apply to any matching system based on types; the difference is that other languages have often already paid the price. For Python it is an incremental cost incurred by the match system. -jJ ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
At 06:10 PM 04/21/2005 +0100, Michael Hudson wrote: But the visitor pattern is pretty grim, really. It would be nice (tm) to have something like: match node in: Assign(lhs=Var(_), rhs=_): # lhs, rhs bound in here Assign(lhs=Subscr(_,_), rhs=_): # ditto Assign(lhs=Slice(*_), rhs=_): # ditto Assign(lhs=_, rhs=_): raise SyntaxError in Lib/compiler. FWIW, I do intend to add this sort of thing to PyProtocols' predicate dispatch system. Actually, I can dispatch on rules like the above now, it's just that you have to spell out the cases as e.g.: @do_it.when("isinstance(node, Assign) and isinstance(node.lhs, Subscr)") def do_subscript_assign(node, ...): ... I'd like to create a syntax sugar for pattern matching though, that would let you 1) use a less verbose way of saying the same thing, and 2) let you bind the intermediate values to variables that then become accessible in the function body as locals. Anyway, the main holdup on this is deciding what sort of Python syntax abuse should represent variable bindings. :) Maybe something like this will be suitably horrific: @do_it.when("node in Assign.match(lhs=`lhs` in Subscr,rhs=`rhs`)") def do_subscript_assign((lhs,rhs), node, ...): ... But I think maybe here the cure is worse than the disease. :) Pushed this far, it seems to beg for new syntax to accommodate in-expression variable bindings, something like 'var:=value'. Really, though, the problem is probably just that inline variable binding is downright unpythonic. The only time Python does anything vaguely similar is with the 'except type,var:' syntax. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
On 4/21/05, Michael Hudson <[EMAIL PROTECTED]> wrote: > Shannon -jj Behrens <[EMAIL PROTECTED]> writes: > > > On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> 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. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Samuele Pedroni <[EMAIL PROTECTED]> writes: > Michael Hudson wrote: [pattern matching] >>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. That's a better way of putting it than "pattern matching and python don't really seem to fit together", for sure :) (I'd quite like records with labels, tangentially, but am not so wild about ordering) > 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. But the visitor pattern is pretty grim, really. It would be nice (tm) to have something like: match node in: Assign(lhs=Var(_), rhs=_): # lhs, rhs bound in here Assign(lhs=Subscr(_,_), rhs=_): # ditto Assign(lhs=Slice(*_), rhs=_): # ditto Assign(lhs=_, rhs=_): raise SyntaxError in Lib/compiler. Vyper had something like this, I think. > > 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). Yikes! > 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. Also, the syntax is disgusting. But that's a separate issue, I guess. Cheers, mwh -- /* I'd just like to take this moment to point out that C has all the expressive power of two dixie cups and a string. */ -- Jamie Zawinski from the xkeycaps source ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] Re: switch statement
I wrote: > Now the pattern matching is more interesting, but again, I'd need to > see a proposed syntax for Python before I could begin to consider it. > If I understand it properly, pattern matching in Haskell relies > primarily on Haskell's excellent typing system, which is absent in > Python. Nick Coghlan replies: > There's no real need for special syntax in Python - an appropriate tuple > subclass will do the trick quite nicely: [... sample code matching tuples ...] Aha, but now you've answered my question about syntax, and I can see that your syntax lacks most of the power of Haskell's pattern matching. First of all, it can only match tuples ... most things in Python are NOT tuples. Secondly (as Michael Walter explained) it doesn't allow name binding to parts of the pattern. Honestly, while I understand that pattern matching is extremely powerful, I don't see how to apply it in Python. We have powerful introspective abilities, which seems to be helpful, but on the other hand we lack types, which are typically a key feature of such matching. And then there's the fact that many of the elegent uses of pattern matching use recursion to traverse data structures... a no-no in a CPython that lacks tail-recursion elimination. There is one exception... matching strings. There we have a powerful means of specifying patterns (regular expressions), and a multi-way branch based on the content of a string is a common situation. A new way to write this: s = get_some_string_value() if s == '': continue; elif re.match('#.*$', s): handle_comment() elif s == 'DEFINE': handle_define() elif s == 'UNDEF': handle_undefine() elif re.match('[A-Za-z][A-Za-z0-9]*$', s): handle_identifier() else: syntax_error() would be might be nice, but I can't figure out how to make it work more efficiently than the simple if-elif-else structure, nor an elegent syntax. -- Michael Chermside ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Michael Hudson wrote: Shannon -jj Behrens <[EMAIL PROTECTED]> writes: On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> 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. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
On 4/21/05, Nick Coghlan <[EMAIL PROTECTED]> wrote: > Michael Chermside wrote: > > Now the pattern matching is more interesting, but again, I'd need to > > see a proposed syntax for Python before I could begin to consider it. > > If I understand it properly, pattern matching in Haskell relies > > primarily on Haskell's excellent typing system, which is absent in > > Python. > > There's no real need for special syntax in Python - an appropriate tuple > subclass will do the trick quite nicely: You are missing the more interesting part of pattern matching, namely that it is used for deconstructing values/binding subvalues. Ex.: case lalala of Foo f -> f Bar (Baz brz) _ meep -> (brz, meep) or Python-ish: match doThis() with: Foo as f: return f (_,* as bar,_): return bar Baz(boink as brzzz, meep=10): return brzzz "* as bar" is Not Very Nice (tm) :/ Michael ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Michael Chermside wrote: Now the pattern matching is more interesting, but again, I'd need to see a proposed syntax for Python before I could begin to consider it. If I understand it properly, pattern matching in Haskell relies primarily on Haskell's excellent typing system, which is absent in Python. There's no real need for special syntax in Python - an appropriate tuple subclass will do the trick quite nicely: class pattern(tuple): ignore = object() def __new__(cls, *args): return tuple.__new__(cls, args) def __hash__(self): raise NotImplementedError def __eq__(self, other): if len(self) != len(other): return False for item, other_item in zip(self, other): if item is pattern.ignore: continue if item != other_item: return False return True Py> x = (1, 2, 3) Py> print x == pattern(1, 2, 3) True Py> print x == pattern(1, pattern.ignore, pattern.ignore) True Py> print x == pattern(1, pattern.ignore, 3) True Py> print x == pattern(2, pattern.ignore, pattern.ignore) False Py> print x == pattern(1) False It's not usable in a dict-based switch statement, obviously, but it's perfectly compatible with the current if/elif idiom. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
RE: [Python-Dev] Re: switch statement
Andrew McGregor writes: > I can post an alternative, inspired by this bit of Haskell [...] > 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. If we're going to be evaluating a series of booleans, then the One Proper Format in Python is: if : elif : elif : else: When people speak of introducing a "switch" statement they are speaking of a construct in which the decision of which branch to take requires time proportional to something LESS than a linear function of the number of branches (it's not O(n) in the number of branches). Now the pattern matching is more interesting, but again, I'd need to see a proposed syntax for Python before I could begin to consider it. If I understand it properly, pattern matching in Haskell relies primarily on Haskell's excellent typing system, which is absent in Python. -- Michael Chermside ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
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 <[EMAIL PROTECTED]> writes: On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> 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@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/ andrew%40indranet.co.nz ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
Shannon -jj Behrens <[EMAIL PROTECTED]> writes: > On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> 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@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
Re: [Python-Dev] Re: switch statement
On 4/20/05, M.-A. Lemburg <[EMAIL PROTECTED]> wrote: > Fredrik Lundh wrote: > > PS. a side effect of the for-in pattern is that I'm beginning to feel > > that Python > > might need a nice "switch" statement based on dictionary lookups, so I can > > replace multiple callbacks with a single loop body, without writing too > > many > > if/elif clauses. > > PEP 275 anyone ? (http://www.python.org/peps/pep-0275.html) > > 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. -jj -- I have decided to switch to Gmail, but messages to my Yahoo account will still get through. ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com
[Python-Dev] Re: switch statement
Fredrik Lundh wrote: PS. a side effect of the for-in pattern is that I'm beginning to feel that Python might need a nice "switch" statement based on dictionary lookups, so I can replace multiple callbacks with a single loop body, without writing too many if/elif clauses. PEP 275 anyone ? (http://www.python.org/peps/pep-0275.html) 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. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 20 2005) >>> Python/Zope Consulting and Support ...http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ___ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com