Problem with C++ ranges also exhibited by D
aliak
something at something.com
Tue Apr 16 18:49:30 UTC 2019
On Tuesday, 16 April 2019 at 12:07:03 UTC, Atila Neves wrote:
> This blog post shows off some problems with the ranges v3
> library that is going to be included in the C++20 standard
> library:
>
> https://www.fluentcpp.com/2019/04/16/an-alternative-design-to-iterators-and-ranges-using-stdoptional/
>
> Because the problem is basically (from the blog) "Is it really
> necessary to have separate operations for advancing the
> iterator and evaluating its element?". The answer is of course
> no, and this has been brought up in the forums before. Like it
> or not, D has the same issue:
>
> -----------------------------
> import std.algorithm;
> import std.range;
> import std.stdio;
>
> void main() {
> iota(1, 6)
> .map!((n) { writeln("transform ", n); return n * 2; })
> .filter!(n => n % 4 == 0)
> .writeln;
> }
> -----------------------------
>
> Produces the output:
>
> [transform 1
> transform 2
> transform 2
> 4transform 3
> transform 4
> , transform 4
> 8transform 5
> ]
>
> Showing that the mapped function is called more times than
> strictly necessary, just as in C++.
You can implement map to not do that as well:
https://run.dlang.io/is/9a2ba4
Take that with a grain of salt though, no idea what kind of
corner cases the actual map from phobos deals with.
Also, Ali pointed out strong exception guarantees. There's an
article form Hurb Sutter on implementing a generic stack
container [0] that explains this scenario well. It basically
boils down to, if you have advance and evaluate in one function,
it makes it impossible/awkward for the caller to write exception
correct code. This pattern in particular (code to match the
article link you posted)
try {
auto element = range.next;
// Do something with element
} catch (Exception ex) {
// meh, ignore
}
if copying/assigning can throw, your top element is lost.
Cheers,
- Ali
[0]
http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/aw/meyerscddemo/DEMO/MAGAZINE/SU_DIR.HTM#dingp39
More information about the Digitalmars-d
mailing list