3 ms·
Yeah, it makes sense. It's just a bummer when switch feels like a much better-named keyword for the functionality, in the long term. You almost wonder if they
by mikepurvis 7y ago
Yeah, it makes sense. It's just a bummer when switch feels like a much better-named keyword for the functionality, in the long term.
You almost wonder if they could do something like how `enum` got fixed up with proper scoping as `enum class`. Like, could `switch` retain the legacy functionality with the new stuff triggered when you do `switch from`, `switch if`, or similar. Or there could be new keyword added after the parenthesis, something like:
switch(<thing>) cases {
<opt1> : ...;
<opt2> : ...;
__ : ...;
}
This has a clear connection back to the legacy command in terms of a switch always having either case labels or a cases structure. And zero chance of breaking existing code, given that the `cases` keyword would only be valid in that position and could still be used as an identifier elsewhere (though obviously that would be discouraged).
- twic 7y agoOr even just have a rule that if a switch uses patterns, it can't have any of the weird legacy misfeatures.
- mikepurvis 7y agoI think it's just hard because they really are completely different in behaviour. A conventional switch is just selecting an integer value— under the hood it can be a jump table, a binary search, or something else entirely. This, on the other hand, is always going to be an if-cascade.
- twic 7y agoThat's an implementation question, which seems orthogonal to questions of syntax and semantics. As for efficiency, we have decades of experience of compiling pattern matching, so i would be surprised if it was always just an if-else ladder. The authors of the proposal to add it to Java think that, compared to explicit if-elses, "it is more optimizable too; in this case we are more likely to be able to do the dispatch in O(1) time": https://openjdk.java.net/jeps/8213076 https://openjdk.java.net/jeps/8213076 I imagine this is through approaches which convert the cases to integers, and then do a traditional jump table etc.
- int_19h 7y ago"inspect" is weirdly apropos, because it hearkens back to Simula-67 (which used it for what we'd call type switch today - so, a subset of pattern matching). The original C++ syntax borrowed a lot from Simula.