On 2010-01-29 12:53:27 -0500, Andrei Alexandrescu <seewebsiteforem...@erdani.org> said:

An algorithm can fail in many silent ways if it misuses the range interface. None of std.algorithm algorithms uses front naively.

Easy to say. How did you verify that?

The problem is very subtle: if you call front after popFront on something like byLine which adds a buffer on top of another range, it'll eat one or more element on the downstream range that will be lost if you dispose of the filtering range. It won't have any effect on algorithms using the filtering range in itself, only on those using both the filtering range and the downstream range in tandem.

So basically, if you have an algorithm that calls front after popFront, that algorithm cannot be used reliably for ranges filtering a stream when that stream is also used directly, or used via other filtering ranges. There's no way to enforce that as it becomes the user's problem.

Whereas if input ranges only define 'take', it's pretty easy for the compiler to tell you an algorithm needs a buffer, so you add an intermediary buffer range yourself and you're now aware of the consequences.


Can you run a basic algorithm on a Java stream and on an array as well?

Java lacks templates, and thus lack compile-time duck typing and work only with bytes. But you could iterate on an array as if it was a stream:

        class ArrayStream {
                byte[] array;
                int pos;

                ArrayStream(byte[] array) {
                        this.array = array;
                        pos = 0;
                }

                int read() {
                        if (pos > array.length)
                                return -1;
                        else
                                return array[pos++];
                }
        }

I'm not trying to say that Java streams are superior to ranges, but they don't have unintended buffering issues.

--
Michel Fortin
michel.for...@michelf.com
http://michelf.com/

Reply via email to