March 20, 2017Re: Is it std.regex, or is it me.
On Monday, March 20, 2017 14:36:32 Russel Winder via Digitalmars-d-learn wrote: > Given the following, where X and Y mark the spot: > > X epochRegex = regex("([0-9])+:"); > Y aEpochCapture = matchFirst(aVersionString, epochRegex); > Y bEpochCapture = matchFirst(bVersionString, epochRegex); > > If X or Y are const or immutable the code fails to compile. Only if both X and Y are auto does this code compile. So question to the audience: how do you do single assignment programming in D? Is it, in fact, impossible to program with bindings rather than variables in D? > > And yes this does seem to be a violation of the Principle of Least Surprise. They're variables even if they're const or immutable. To avoid having a variable, you'd need to use enum, which would then require that it work at compile time. In general though, making things const or immutable requires a lot of extra copying in order to make it work, so I don't think that it's all that surprising when something doesn't work with them. Code _can_ be made to work with const and immutable; it's just that there's often a significant cost to doing so. And since D's const and immutable are transitive and don't have backdoors, you can't get around them like you would in C++ (where on some level, const is actually a lie, albeit a convenient one). So, a lot of the time, folks simply don't bother to make their code work with const. What the deal with std.regex is, I don't know, since I've never done much with it, but if ranges are involved, then const definitely doesn't work, because D's const and ranges are pretty much fundamentally incompatible. Ranges mutate in order to iterate. In order to get around that, we'd need a generic way to get a tail-const version of a range, which we definitely don't have. It works with dynamic arrays, because the compiler understands those, but it would be a much more difficult thing to sort out with a user-defined type and would almost certainly require a language change to do so. But ranges aside, I would expect code that worked well with const or immutable to be written specifically with them in mind rather than just happening to work with them. - Jonathan M Davis
Copyright © 1999-2017 by the D Language Foundation