SWITCH
A value looked up in a dictionary or a list, with a value for when it isn't there.
Syntax
SWITCH(value,{case:result,case:result,…},otherwise)
SWITCH(value,{result,result,…},otherwise)
SWITCH(value,table,otherwise)
SWITCH(value,table)
| Argument | Meaning |
|---|---|
| value | What is looked up. |
| {case:result,…} | A dictionary: the result for each case. |
| {result,…} | A list: value says which result, from 0. |
| table | Any expression that gives a dictionary or a list: a variable that holds one, say. |
| otherwise | What to give when value isn't a case of the dictionary, or a position in the list (optional). |
Result
The result for value, or otherwise.
Examples
In the example drawing:
| Expression | Gives |
|---|---|
SWITCH(2,{1:"one",2:"two"},"many") |
"two" |
SWITCH(5,{1:"one",2:"two"},"many") |
"many" |
SWITCH(L,{500:10,600:12},8) |
10 |
SWITCH(1,{"zero","one","two"},"many") |
"one" |
SWITCH(3,{"zero","one","two"},"many") |
"many" |
SWITCH(1.5,{"zero","one","two"},"none") |
"none" |
Notes
With no otherwise, a value that isn't in the table is an error.
With the table written out in the SWITCH, only what is needed is worked out: the cases in turn until one matches, then its result (so a result that couldn't be worked out, such as a division by 0, does no harm unless it is chosen). A table held in a variable is worked out whole.
A list's positions are whole numbers from 0; any other value (1.5, -1, a string) gives otherwise.
See also: Lists and dictionaries, ? :, == != ~=.