Random string samples & unicode - Reprise

bearophile bearophileHUGS at lycos.com
Sun Sep 12 17:09:04 PDT 2010


Andrei Alexandrescu:
> This goes into "bearophile's odd posts coming now and then".

I assume you have missed most of the things I was trying to say, maybe you have not even read the original post. So I try to explain better a subset of the things I have written.

This is a quite common piece of Python code:

from random import sample
d = "0123456789"
print "".join(sample(d, 2))


I need to perform the same thing in D.
For me it's not easy to do that in D2 with Phobos2.

This doesn't work:

import std.stdio, std.random, std.array, std.range;
void main() {
    string d = "0123456789";
    string res = array(take(randomCover(d, rndGen), 2));
    writeln(res);
}

It returns:
test.d(4): Error: cannot implicitly convert expression (array(take(randomCover(d,rndGen()),2u))) of type dchar[] to string


If I change it like this:

import std.stdio, std.random, std.array, std.range;
void main() {
    string d = "0123456789";
    dchar[] res = array(take(randomCover(d, rndGen), 2));
    writeln(res);
}

It doesn't work, and gives a cloud of errors:

...\dmd\src\phobos\std\random.d(890): Error: cast(dchar)(this._input[this._current]) is not an lvalue
...\dmd\src\phobos\std\random.d(907): Error: template std.random.uniform(string boundaries = "[)",T1,T2,UniformRandomNumberGenerator) if (is(CommonType!(T1,UniformRandomNumberGenerator) == void) && !is(CommonType!(T1,T2) == void)) does not match any function template declaration
...\dmd\src\phobos\std\random.d(907): Error: template std.random.uniform(string boundaries = "[)",T1,T2,UniformRandomNumberGenerator) if (is(CommonType!(T1,UniformRandomNumberGenerator) == void) && !is(CommonType!(T1,T2) == void)) cannot deduce template function from argument types !()(int,uint,MersenneTwisterEngine!(uint,32,624,397,31,-1727483681u,11,7,-1658038656u,15,-272236544u,18))


If I replace the d string with a dchar[], it works:

import std.stdio, std.random, std.array, std.range;
void main() {
    dchar[] d = "0123456789"d.dup;
    dchar[] res = array(take(randomCover(d, rndGen), 2));
    writeln(res);
}


But now all strings in this little program are dchar arrays.

What I am trying to say is that with the recent changes to the management of the strings in std.algorithm, when you use strings and char arrays, and you use algorithms over them, the dchar becomes viral, and you end using in most of the code composed dchar arrays or dstrings (unless you cast things back to char[]/string, and I don't know if this is possible in SafeD).

Do you understand now? I am mistaken?

Bye,
bearophile


More information about the Digitalmars-d mailing list