Function form of the more verbose
switch() { case:...; default: ..}
which is called as
Switch(value, key1=expr1, key2=expr2,..., expr)
The first argument is the value we use to identify
the actual case of interest. At present, we convert
it to a String and then examine each of the
remaining arguments. For those that have names (i.e. of the
form keyi = expr1), we compare the left hand side of
the assignment to the value String. On the first match,
we evaluate the right hand side and return it.
If none of the named arguments match, we return the
unnamed argument which acts as the default
case.
Examples
[] x = 1
[] Switch(x, 1="First one", 2="Second one", "Neither of these")
First one
[] x = 3
[] Switch(x, 1="First one", 2="Second one", "Neither of these", 4="Fourth")
This uses compiled Java code and so is faster than
an interpreted version. Since it can be added and removed
from the evaluator dynamically using the
addFunctionTable(), we stil have many of the
advantages of using interpreted functions.
Based on the limitations of the parser, etc.
using this does not provide the same flexibility
as the regular switch statement.
Many complicated expressions such as for loops, etc. cannot be
supplied as arguments. It is very useful in many common circumstances
behaving as a convenient if-else statement where each conditional
clause is a simple call.
More complicated expressions can be used in this
method.
They can be stored in a two step operation
e = parse("for(i in 1::10) { show(i);}")
Switch(x, a = e, "Nothing to do")
However, this will not evaluate the expression
stored in e, just the expression
e itself. Hence, one would be returned the
enumerated for-loop.
This cannot be named switch since we would get
parser errors when referring to it since that is a reserved
keyword in Java and Omegahat.
Reasons for introducing this as a function
include speed and also avoiding reserializing the function
definition each time we change class definitions.