Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Marko Rauhamaa Newsgroups: comp.lang.python Subject: Re: Case Statements Date: Wed, 16 Mar 2016 16:31:51 +0200 Organization: A noiseless patient Spider Lines: 78 Message-ID: <87mvpycx48.fsf@elektro.pacujo.net> References: <30502a2e-0bad-4b0f-a1e8-a2b40b0d7ab9@googlegroups.com> <56E928D4.3000701@rece.vub.ac.be> <56E93ADD.9040500@rece.vub.ac.be> <87vb4md362.fsf@elektro.pacujo.net> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="b7cb1518d23ec19d482dcc9c31d30fdd"; logging-data="12629"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19BjXfWiqF8BPfHZkYTJ62U" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/24.5 (gnu/linux) Cancel-Lock: sha1:8bxIhKHxD4e8ZA+1or/JxKAUtow= sha1:P7R6blNLBpCz2aDnkwCUAYTZsww= Xref: csiph.com comp.lang.python:105035 BartC : > Yes, a few scripting languages can do interesting things with switch or > case statements. Perl for example (where I think it is created out other > language features, but it looks a regular part of the syntax). > > Even Ruby has one. It doesn't do anything 'sexy' with it, but it does > have this: > > case > when this > .... > when that > .... > when other > ... > end That's a different topic. > which is exactly equivalent to if this... elif that... (when the tests > are ordered), with one difference: > > Each test starts with "when", instead of "if" for the first and "elif" > for subsequent ones. That makes it easier to reorder tests, temporarily > comment out the first test, copy a test from elsewhere, insert a new > first test (you get the idea). That is no different from a chained if/elif. Scheme has this: (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite) (else 'unknown)) It has something better than C even: (case (die10) ((1 3 5 7 9) => (lambda (n) n)) (else => (lambda (n) (/ n 2)))) which maps 1, 3, 5, 7 and 9 onto themselves but halves 2, 4, 6, 8 and 10. As for a chained if/elif, Scheme as "cond:" (cond ((windy?) (fly-kite)) ((shining? sun) (go-out)) ((raining?) (play-soccer)) (else (read-book))) which also has a "=>" variant: (cond ((best-selling-book (this-year)) => (lambda (book) (read book))) (else (play wii pes08))) Marko PS What is a "scripting language?"