Case Statements

Marko Rauhamaa marko at pacujo.net
Wed Mar 16 10:31:51 EDT 2016


BartC <bc at freeuk.com>:

> 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?"



More information about the Python-list mailing list