42 ms·
C++ Pattern Matching Proposal [pdf]
- typon 7y agoWhy call it inspect instead of match?
- de_watcher 7y agoBecause of regex.
- mkl 7y agoThe regex header doesn't seem to define anything called "match". It is probably a common variable name though. To me "inspect" implies the wrong action, so it would be nice if there was a better keyword.
- Sharlin 7y agoInspect breaks less existing code.
- kevin_thibedeau 7y agoThey ought to use "_Inspect".
- rightbyte 7y agoDoes this proposal have any support? At first it seems nice, but is it realistic to add so much new syntax to the language?
- de_watcher 7y agoStructured bindings need to get rid of the mandatory dummy variables in case of the unused parts of the structure. So something has to be added.
- gumby 7y agoSomething has to be added but it could just be an empty comma, which IIRC parallels initialization: use `auto& [a, , c]` to match the first and third elements of a tuple.
- quizotic 7y agoThis seems so much more clear to read, with less typing.
- rb808 7y agoIts seems all languages are just copying each other at this point. I know C++ hates to be left out of anything so maybe this is appropriate, but to me its really destroying the ecosystem. It was great to have different languages having different paradigms but now you can do everything in everything and code bases I'm working on are a confusing mess.
- agumonkey 7y ago> each other by each other you mean the ml world right ? :p
- vmchale 7y agoFunctional programming seems to be taking on the world (J inspiring NumPy, ML features being used everywhere).
- agumonkey 7y agoYes, haskellers will soon be celebrities.
- gdxhyrd 7y agoFunctional languages are nowhere to be seen compared to the rest. Some subset of features inspired in them are used in some languages, but that has nothing to do with functional programming taking over.
- agumonkey 7y agoHonestly even if we're far from FP as mainstream (which I don't even wish). I woudln't have bet a dollar that so much features from lisp/ml would have crossed over this fast (I mean destruct, lambda, rest args, immutable let by default, option chaining ..).
- vmchale 7y ago> option chaining Where'd that come from? I thought that was monadic-do from Haskell.
- greg7mdp 7y agoLove this proposal! C++ is getting better in leaps and bounds.
- vunie 7y agoIt's amazing what credible competition can do. If only C had the same kind of pressure.
- eps 7y agoDon't you even dare. C is near-perfect in the simplicity of its core. You want bells and whistles, you hook up a library.
- billfruit 7y agoC has many rough spots too, especially in organising large and complex programs. There is always scope for innovation and improvements.
- user5994461 7y ago>>> There is always scope for innovation and improvements. but not in C because C has no scope
- weberc2 7y agoCould you refer me to a good/standards-compliant library for typesafe generic lists, hashmaps, pattern matching, closures, etc?
- huhtenberg 7y agoYou are missing the main strength of C - the transparency and predictability of what machine code gets generated from the source code. When you write "a + b", you won't end up with kilobytes of machine code just because someone in some header overloaded the + operator. Ditto for template-style generics and overloaded functions. If you call a function and it doesn't exist, it won't get auto-generated for you on the fly. You get an error. You want a function, you define that function. That's not the flaw of the language. That's its strength. Ditto for switch-case constructs. Ditto for closures. All of these constructs, should they be added to the language, will result in a compiler generating heaps of code from a simple code snippet. But this will no longer be C, because in C what you see is what you get.
- antiquark 7y agoTheir example #4.3 won't always produce the same result as the "if" version, because x==x and y==y could return false due to operator overloading.
- wereHamster 7y agoIf you overload the == operator such that x==x is false then I call UB. Reading and understanding such a codebase would be a nightmare.
- 0xffff2 7y agoIs it actually UB or just stupid? I've never tried to dig in and understand C++ at the standards level, so I don't know, but you don't get to just "call" UB; it has to be UB by the standard.
- Karliss 7y agoBy itself it is just stupid. Standard defines "EqualityComparable" property and which parts of STL require it to be satisfied. There even some places where it notes that EqualityComparable property isn't required. It is much easier to get UB by having bad < operator.
- fyp 7y agoNaN == NaN is always false (at least in other languages I know).
- kibwen 7y agoThis will be the case in any language that confirms to IEEE 754 (so, hopefully, all of them (because the only thing more confusing than properly implementing IEEE 754 is improperly implementing your own bespoke subset)). This property of NaN is required by the spec (and is, for example, why Rust's default HashMap refuses to accept floating point numbers as keys).
- umanwizard 7y ago
- thurn 7y agoanything in here about exhaustiveness checking? In my mind that's half the value of pattern matching.
- SloopJon 7y agoFrom the Exhaustiveness and Usefulness section: "inspect can be declared [[strict]] for implementation-defined exhaustiveness and usefulness checking." "having a __: case makes any inspect statement exhaustive." "any case that comes after a __: case would be useless"
- jobstijl 7y agoWhy wouldn't they make it [[strict]] by default?
- atilaneves 7y agoBecause it's C++, and the defaults must suck (std::vector::at anyone?)
- 0xffff2 7y agoJust skimming section 4, this really just looks like even more syntax being added to the language without enough benefit to justify the additional complexity. At this point, I think I've made the decision to just stick with C++11 indefinitely and backport the rare useful feature. I don't want to have to memorize all of this extra stuff.
- xscott 7y agoWhat we need is a compiler flag that says, "give me the good parts of C++11/14, but leave out the bad stuff from C++98, and fix some of the inconsistency quirks from trying to be compatible with C89".
- harikb 7y agoThis works so long as entire build is your own code. Once you get to libraries written by someone else who happens to have a different “wish list”, I would guess this flags idea wouldn’t work well.
- falcor84 7y agoCould you please explain more about the process you're using? Are you compiling external dependencies as an integral part of building your own code?
- derefr 7y agoThey’re using some header-only libraries, presumably. Which, after all, is one of the only unique benefits of C++ that would lead you to choose it for a green-field project over, say, Rust. Header-only template libs + link-time WPO = inlining of template-instantiated monomorphized methods to their type-strict callers. This is the feature that leads e.g. LLVM to be written in C++.
- steveklabnik 7y agoRust doesn’t have headers, but can still do this.
- toolslive 7y agocompare this proposal to the pattern matching you get from Haskell or OCaml and weep. for example (OCaml): let imply = function | (true,false) -> false | _ -> true
- macintux 7y agoPattern matching across multiple function heads (ML, Erlang) is incredibly liberating. I hear Haskell has it but it's not idiomatic, and I think Elm doesn't support it at all. Frustrating. I've found half-hearted pattern matching solutions like Scala quite disappointing.
- lalaithion 7y agoCan you give an example of the pattern matching in ML and Erlang that is not idiomatic in Haskell?
- macintux 7y agoIt's the multiple function heads which (again, I've been informed, no direct knowledge) is discouraged. e.g. https://github.com/macintux/advent-of-code-2019/blob/master/day4/day4.erl#L34-L41 https://github.com/macintux/advent-of-code-2019/blob/master/...
- p0llard 7y agoYou mean a piecewise definition of a function? I don't think this is unidiomatic or discouraged in Haskell at all.
- macintux 7y agoThere's some indirect discussion here that seems to contradict that, but I certainly could be wrong. https://github.com/elm/compiler/issues/973 https://github.com/elm/compiler/issues/973
- amelius 7y agoDoes the D language have pattern matching?
- deleted 7y ago[deleted]
- atilaneves 7y agoNo. But it can be done as a library. Granted, it's not the same as 1st class support, but it's pretty good: https://github.com/pbackus/sumtype https://github.com/pbackus/sumtype
- ape4 7y agoI know this is different than the regex library but just thought I'd mention... Declaring regex's like javaScript with be cool. var myre = /^hello\w*/; std::regex myre("^hello\\\w*");
- mikepurvis 7y agoReading over the examples, it seems like there's a lot of good stuff here, though I wondered how possible it would be to extend switch with some of this capability vs adding a new keyword. It looks like this possibility was considered and is addressed in §7.2— basically the flexibility of case labels and break statements being able to appear inside control structures leads to all kinds of chaotic corner cases for switch (Duff's Device and friends) that are incompatible with the proposed semantics for inspect, with no obvious way to signal from the source which one you want.
- jupp0r 7y agoSeems like `inspect` would turn `switch` into a deprecated practice, which is preferable imho. This way, it's easier to write clang-tidy rules for conversion and to raise red flags in PRs.
- mikepurvis 7y agoYeah, 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.
- 7y ago
- kabdib 7y ago"It must be our great task, gentlemen, to keep the monkeys away from the typewriters." -- H. L. Mencken
- specialist 7y agoI really like the proposal for matching values (integral, strings, tuples). It's very lispy. Explicit representation (intrinsics?) of a map used as an expression. Though I would prefer the keyword 'choose' over 'inspect'. -- I have noob questions about pattern matching on (polymorphic) types. Please humor: It's syntactic sugar for std::is_base_of<> (Java's instanceof), right? This is a consequence of C++ (and Java's) nominal type system, right? So is pattern matching on types necessary (useful) for structural type systems? I ask because a friend has been advocating structural typing. He's more of a language theorist whereas I'm more of a language mechanic (I don't even rate as a language engineer). While I'm totally on board with whatever he says, I just hope to better grasp the changes.
- jokoon 7y agoI don't understand why some people don't like C++. It almost seems like they forget what it means to compile to machine code. I can say I have some sort emotional attachment to python, but I can't deny that C++ is just a more capable language, but at least I can admit that I'm just not always competent to always write C++. Like most people say "just use the parts of C++ you need".
- dullgiulio 7y agoThankfully C++ is far from the only language that compiles to native. Many others don't even have the same insane "features".
- jokoon 7y agoThere are not that many languages with good support that compile to native.
- pjmlp 7y agoJava (yes it does, since around 2000), .NET (NGEN since v1.0, Mono AOT, IL2CPP, .NET Native), D, Eiffel, FreePascal, Delphi, RemPascal, Swift, OCaml, Haskell, Lisp, Ada, Scheme, Basic, Go, Fortran. Just a couple of possible languages, there are many more if we take out the good support constraint.
- jokoon 7y agoGarbage collected languages are not really native languages. I don't see good enough alternatives to C++, which have enough support, not a steep learning curve, good backward compatibility with existing ecosystems, not owned by a single company, etc.
- umanwizard 7y agoDepending on your definition of "enough support", Rust might be what you want. > not a steep learning curve well, it's steeper than most languages, but less so than C++ IMO, especially if you're already familiar with C++ and therefore understand the problems Rust is intended to solve.
- crazypython 7y agoHow does this work compared to ML's signatures?
- oaiey 7y agoTo my understanding, this capability set is roughly the same as what C# 8.0 support and what Java also targets. Just with a different keyword.
- gumby 7y agoI would wish for it to work with concepts and state. Then you could write a simple production system in the spirit of Prolog, Erlang, et al. The multi-argument generics is partway down that path, so why not go all the way.
- abjKT26nO8 7y agoMore syntax, more semantics - because that's exactly what C++ needed. At this point I think they may be competing in the most complex languages championship. When are the next Olympic Games? And it's not like we could just abstain from using new parts of the language. For every feature there is going to be a person who will be excited to use it in an open source project which your company depends on, and sooner or later you're going to have to pay for every inch of complexity introduced to the language. But the people in charge seem to think that there is no cost to it.
- LessDmesg 7y agoNo amount of new features will ever vindicate C++. The language is so complex and so flawed on every level that it can only be deprecated and migrated away from. The only way to save developer time and woes is not to produce any new lines of C++.
- ryuukk_ 7y ago"inspect" what a horrible choice