* change switch statements to check `switchExpression ~= caseExpression`
// in Pattern
bool operator ~=(Object other) => this.hasMatch(other); // or just replace hasMatch method
// in Collectionbool operator ~=(Object other) => this.contains(other); // see http://dartbug.com/1030
FWIW, Perl uses a similar operator (~~ called "smart match") as the
basis for its switch statement (given-when). See
http://perldoc.perl.org/perlsyn.html#Switch-statements I've found it
to be a very powerful and clear way of expressing flow control.
Nearly every non-trivial Perl program I write uses a given-when
construct.
With Dart's operator overloading, Sean's proposal would be especially
powerful. I like it.
--
Michael
With Dart's operator overloading, Sean's proposal would be especially
powerful. I like it.
which ((pattern) => pattern.matches(input)) {
case RANDOM_GIBBERISH: smackMonkey();
case VALID_POEM: dispenseBanana();
default: issueEncouragement("Nearly there!");
My only hesitation is that case looks like a variable embedded in an
arbitrary expression, but since it's not a variable,
speccing/implementing this behaviour might be complex. e.g. consider:
switch ((){ switch(x == case) { case 42: ... } }()) {
}
'Obviously' the 'case' being compared to x is from the inner switch,
but only because we know the name-shadowing rules for variables...
The easiest way to solve this might be to turn case into a real
auto-bound variable (maybe called _, since case is a keyword).
> The second syntax is for expressions that do not contain the keyword
> case. For these the case statements take the form "case op?
> expression" where op is any relational operator (ideally is is
> supported as well). If the operator is left out, it is ==.
>
> switch(val) {
> case === obj:
> case is! int:
> case < 0:
> case 0:
> case >= 1:
> }
I don't think this is so useful, because lots of my common use cases
aren't operators (or are operators on the case-value rather than the
switched-value).
What about just switch {...} defaulting to switch(true) {...}
switch {
case val.isEmpty(): ...
case SOME_PATTERN.matches(val): ...
}
To use this you may have to assign the expression to a local (e.g.
final val = readline()) but that doesn't seem too onerous.