Why won't mmutable ranges stack?

Simen kjaeraas simen.kjaras at gmail.com
Sun Dec 26 02:35:37 PST 2010


doubleagent <doubleagent03 at gmail.com> wrote:

> The former works while the latter fails.  It looks like there's some
> manipulation of 'bytes' and 'list' when writefln forces evaluation.  My
> question is should this happen?

void main() {
     immutable auto bytes = splitter(stdin.readln(), ' ');
     immutable auto list = map!(byteToChar)(bytes); // Here
     immutable auto msg = reduce!("a ~ b")("", list);
     writefln("%s", msg);
}

The problem is on the marked line here - map and other non-array ranges
don't deal well with being immutable or const. Remove the immutable part
 from list, and it works wondrously:

void main() {
     immutable bytes = splitter(stdin.readln(), ' ');
     auto list = map!(byteToChar)(bytes); // Here
     immutable msg = reduce!("a ~ b")("", list);
     writefln("%s", msg);
}

Also note that auto is unnecessary when another storage class is
specified (const,immutable).

There have been several asking for tail-const (i.e. const(int)[])
support for ranges other than arrays. I have even written an
implementation that to an extent works, but more language support would
be preferable.


> Also, is there a more idiomatic way to do byte conversions?  Something  
> in the stdlib, perhaps?

std.conv.parse[1] with a second parameter (radix) of 2 works for me:


#!/opt/dmd2/linux/bin/rdmd

import std.stdio, std.algorithm, std.conv;

immutable(char) byteToChar(string b) {
     return cast(char)parse!ubyte(b,2);
}

void main() {
     immutable bytes = splitter(stdin.readln(), ' ');
     auto list = map!(byteToChar)(bytes);
     immutable msg = reduce!("a ~ b")("", list);
     writefln("%s", msg);
}


[1]: http://www.digitalmars.com/d/2.0/phobos/std_conv.html#parse
-- 
Simen


More information about the Digitalmars-d-learn mailing list