std.range.put?

Steven Schveighoffer schveiguy at yahoo.com
Wed May 23 13:27:51 PDT 2012


On Mon, 21 May 2012 07:26:32 -0400, simendsjo <simendsjo at gmail.com> wrote:

> Shouldn't the following work?
>
> import std.range;
> import std.stdio;
>
> void main() {
>      int[] a;
>      a.reserve(10);
>      //a.put(1); // Attempting to fetch the front of an empty array of  
> int
>      a.length = 1;
>      writeln(a.length); // 1
>      a.put(2);
>      writeln(a.length); // 0 - what?
>      writeln(a); // [] - come on!
OK, here is why:

put(R, v) has three modus operandi:

1. R is an input range with an lvalue front().
2. R is a function/delegate that accepts a v
3. R implements the method put(v)

slices fit into category one.  In this case, guess what happens?

R.front = v;
R.popFront();

Why?  Think of R as a *buffer* that is *pre-allocated* and needs to be  
filled.  This is what put is trying to do.

What you want is std.array.Appender, which defines the method put, which  
*appends* data to the end instead of overwriting it.

>      char[] b;
>      //b.put('a'); // range.d(615): Error: static assert  "Cannot put a  
> char into a char[]"
> }

This is just phobos being its usual nasty self claiming that char[] is not  
an array of char, but actually a range of dchar.  If I only had a nickel  
every time someone ran into this "feature"... I'd probably have about $5  
by now ;)  It's one of the worst designs of Phobos.

-Steve


More information about the Digitalmars-d-learn mailing list