Sampling algorithms for D

bearophile bearophileHUGS at lycos.com
Thu Apr 12 15:48:18 PDT 2012


Joseph Rushton Wakeling:

> Thanks ever so much for the extensive review.

They are shallow comments, mostly about syntax, etc. So writing 
them requires little time.


> Is this advised for all D modules, or just for stuff using the 
> C standard library?

I have said "there is also the syntax" instead "it's better to do 
this" because some D programmers don't like to do that. You have 
to be aware that syntax exists, and that's it's better to write:
import std.foo: bar, baz;
Than:
import std.foo; // for bar and baz functions

then personally I sometimes like to qualify my imports (writing 
what I import from them), for various reasons, but it also 
increases the amount of work to do when you want to modify the 
code. So it's a personal choice.
Also, the more important is for you to not put bugs in a specific 
module, the more "tight"/strongly statically typed is better to 
write the code (like Ada language code). If for you the 
correctness of a specific module is not very important, then 
using a lazier coding style is acceptable :-) If you write code 
lot of money/hardware or even people lives will depend on, you 
have to adopt a progressively more and more error-proof style of 
coding, eventually even using software to proof the correctness 
of critical routines.


> Whether I can do this would depend on

It depends on many things, including DMD bugs, D language design 
faults, Phobos incomplete coverage of those annotations, and of 
course on the semantics of your code, etc.


> I want to be _certain_ that value is zero. ;-)

Then assign on more time, to be really sure :-)
int x = 0;
x = 0; // It must be ZERO, dammit.


>        final size_t select(ref UniformRNG urng)
>        {
>              assert(_recordsRemaining > 0);
>              assert(_sampleRemaining > 0);

Probably it's better to move those asserts in 
preconditions/postconditions or in class/struct invariants.
And I think your code needs some unittests{} too.


> Ack, enabling that is precisely why I bothered templatizing it 
> in the first place.  Can you suggest a fix ... ?  I don't 
> understand why as-is it wouldn't work.

If you try to use a Xorshift the compiler will tell you the 
problems, I think with some work you will be able to fix them and 
create a more flexible module:

void main() {
     auto urng = Xorshift(23);


> This stuff I'm not too worried about, because it's only a 
> stupid demo thing, not the important code ... :-)

In my opinion demo code is a bit like unittests. And unittests 
require the same coding precision as the rest of the code :-)

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list