On 09/12/2010 07:09 PM, bearophile wrote:
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))

Well it's not that common code. How often would one need to generate a string that contains two random but distinct digits?

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

The code compiles and runs as written on my system. I think it's David Simcha who changed the return type to ForEachType!Range[]. I'm not sure I agree with that, as it takes an oddity of foreach that I hoped would go away some time and propagates it.

About the original problem: strings are bidirectional ranges of dchar, which is the way they ought to be. Algorithms used on top of strings will inherently traffic in dchar. If you want to get a string back, this should work:

string res = to!string(take(randomCover(d, rndGen), 2));

That doesn't work for a different reason, and is a bug worth filing. In fact - no need, I just submitted a fix (http://www.dsource.org/projects/phobos/changeset/1988). Thanks for bringing this up!


Andrei

Reply via email to