4 ms·
I really like that Ruby throws NoMatchingPatternError if none of the patterns match. It's a bit like the much-acclaimed exhaustive pattern matching in static la
by frou_dh 3y ago
I really like that Ruby throws NoMatchingPatternError if none of the patterns match. It's a bit like the much-acclaimed exhaustive pattern matching in static languages (though at runtime rather than compile-time, obviously) and better than just silently falling off the end, which IIRC is what Python's pattern matching does.
- rusk 3y agoIn Python you can terminate a for loop with else, which will be run whenever the loop runs to the end without breaking
- specialist 3y agoNeat. Will check it out. I recently spotted a (new to me) foreach / else construct in a templating language (sorry, forget which one); else is invoked if the list is empty. Nice sugar for common outputs like "no items found". I appreciate modest syntactic sugar. For instance, my #1 sugar wish is for Java's foreach is to do nothing when the list reference is null. Versus tossing a NPE. Eliminates an unnecessary null check and makes the world a little bit more null-safe.
- rusk 3y ago> else is invoked if the list is empty. for / else should do that too …
- frou_dh 3y agoThat's not particularly relevant to the nice pattern matching property I mentioned. If you need to manually write supplementary code to get the exhaustiveness safety then that's back into the realm of bog-standard defensive programming. Here's what I mean. The Ruby will throw NoMatchingPatternError and the Python will silently do nothing. x = [10, "figs"] case x in [n, "apples"] :foo in [n, "oranges"] :bar end # --- x = [10, "figs"] match x: case [n, "apples"]: ... case [n, "oranges"]: ...
- rusk 3y agoYou can use ‘case _’ in that case … it’s not a big deal to opt into this default behaviour.