Product SiteDocumentation Site

9.2. Switch expressions

Switch expressions are very similar to C++. A switch expression evaluates the expression inside the switch. If it is an atomic, it compares it in turn to the provided atomic values (with the semantics of the eq operator) and returns the value associated with the first matching case clause.
Example 9.4. A switch expression.
switch ("foo")
  case "bar" return "foo"
  case "foo" return "bar"
  default return "none"
Results:
"bar"

If the provided value is not an atomic, an error is raised (this is also similar to C++).
If the value does not match any of the expected values, the default is used.
Note that the default clause is mandatory (but can be the empty sequence)
Example 9.5. A switch expression.
switch ("no-match")
  case "bar" return "foo"
  case "foo" return "bar"
  default return "none"
Results:
"none"

The case clauses support composability of expressions as well - an opportunity to remind you about the precedence of the comma.
Example 9.6. A switch expression.
switch (2)
  case 1 + 1 return "foo"
  case 2 + 2 return "bar"
  default return "none",
switch (true)
  case 1 + 1 eq 2 return "1 + 1 is 2"
  case 2 + 2 eq 5 return "2 + 2 is 5"
  default return "none of the above is true"
Results:
"foo"
"1 + 1 is 2"