www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - A little of coordination for Rosettacode

reply "bearophile" <bearophileHUGS lycos.com> writes:
Is the Fwend user of Rosettacode (or some other interested 
person) around here? I have written partial D implementations for 
three tasks, maybe a little of coordination will speedup the work:

http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
http://rosettacode.org/wiki/Universal_Turing_machine
http://rosettacode.org/wiki/RCRPG

Bye,
bearophile
Feb 04 2013
next sibling parent reply Jos van Uden <usenet fwend.com> writes:
On 5-2-2013 0:55, bearophile wrote:
 Is the Fwend user of Rosettacode (or some other interested person) around
here? I have written partial D implementations
for three tasks, maybe a little of coordination will speedup the work:

 http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
 http://rosettacode.org/wiki/Universal_Turing_machine
 http://rosettacode.org/wiki/RCRPG
I'll give it a shot if you like. The RCRPG I'd like to try first. By the way, I think 'Qznc' may want to have a look at 'The dining philosophers': http://rosettacode.org/wiki/Dining_philosophers
Feb 05 2013
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 I'll give it a shot if you like. The RCRPG I'd like to try 
 first.
I have already partially written those: Partial translation of rcrpg-Python: http://codepad.org/SflrKqbT Partial translation of permutations_rank_of_a_permutation-Python: http://codepad.org/El9SQwOE Plus a better Perl implementation of the uniform() on BigInts: http://codepad.org/LGcMpk2f Partial translation of the universal_turing_machine-Ruby: http://codepad.org/nUXLzAg2 Bye, bearophile
Feb 05 2013
next sibling parent reply Jos van Uden <usenet fwend.com> writes:
On 5-2-2013 21:10, bearophile wrote:

How do we avoid working on the same thing?

 Partial translation of rcrpg-Python:
 http://codepad.org/SflrKqbT

 Partial translation of permutations_rank_of_a_permutation-Python:
 http://codepad.org/El9SQwOE
The 2 above, I could try.
 Plus a better Perl implementation of the uniform() on BigInts:
 http://codepad.org/LGcMpk2f
My perl is too rusty.
 Partial translation of the universal_turing_machine-Ruby:
 http://codepad.org/nUXLzAg2
I'd have to first read up on the subject.
 Bye,
 bearophile
Feb 05 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 How do we avoid working on the same thing?
With a little coordination :-)
 Partial translation of rcrpg-Python:
 http://codepad.org/SflrKqbT

 Partial translation of 
 permutations_rank_of_a_permutation-Python:
 http://codepad.org/El9SQwOE
The 2 above, I could try.
 Plus a better Perl implementation of the uniform() on BigInts:
 http://codepad.org/LGcMpk2f
My perl is too rusty.
That perl is meant as a part of permutations_rank_of_a_permutation. Feel free to search for other good algorithms to implement uniform(BigInt,BigInt) much better than me. If this code comes out good enough, it must be added to Phobos (and it's meant to be designed better than the Java uniform generator for its bigintegers, because it doesn't give a correct range).
 Partial translation of the universal_turing_machine-Ruby:
 http://codepad.org/nUXLzAg2
I'd have to first read up on the subject.
It's a simple task, just to implement an universal Turing machine. It's a matter of finding a balance between the too much high level Ruby version and a too much C-like version. In D a simple way to implement a tape is with two dynamic arrays, one represents all the cells on the right to the starting position, and the other array is used "inverted", to represent all the cells on the left of the right position. There are faster solutions, but this is enough for the purposes of Rosettacode. Bye, bearophile
Feb 05 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 5-2-2013 23:44, bearophile wrote:
 Jos van Uden:
 Partial translation of the universal_turing_machine-Ruby:
 http://codepad.org/nUXLzAg2
I'd have to first read up on the subject.
It's a simple task, just to implement an universal Turing machine. It's a matter of finding a balance between the too much high level Ruby version and a too much C-like version. In D a simple way to implement a tape is with two dynamic arrays, one represents all the cells on the right to the starting position, and the other array is used "inverted", to represent all the cells on the left of the right position. There are faster solutions, but this is enough for the purposes of Rosettacode.
The Universal Turing Machine is working. I've only tested with the given tables. I'll try some more tomorrow. I couldn't get the AA's to nest the way they do in Ruby, so I had to do it differently. This task seemed like a good candidate for using an invariant, but the loop in the run method already checks the state on every iteration, so I'm not sure what you could check except to see if all the fields have been initialized perhaps. It was a fun task. http://dpaste.dzfl.pl/3caa52e7
Feb 15 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 The Universal Turing Machine is working.
There are many different ways to solve this Task in D. You can write a very strongly typed Ada-like program, or a weakly typed Ruby-like program. Both have advantages and disadvantages (as years pass I am leaning more toward a stronger static typing, despite I like Python). Your version is more toward the weakly typed end of the spectrum (but not as much as Ruby). I am now reading your code. - - - - - - - - - - This is bad: void move(in int dir) { final switch(dir) { case UTM.left: left(); break; case UTM.right: right(); break; case UTM.stay: stay(); break; } } "final switche" was introduced in D to increase safety making the code more strongly typed, but there you are relying on a DMD bug, and that piece of code is the opposite of safe. A correct D compiler must refuse your code: http://d.puremagic.com/issues/show_bug.cgi?id=5713 I have rewritten it like this: void move(in int dir) { switch(dir) { case UTM.left: left(); break; case UTM.right: right(); break; case UTM.stay: stay(); break; default: assert(0); } } If you want to write a stronger typed code you can give a name to that enum, and then it's a good idea to use a final switch. But then the associative array "rules" must have Tuples (or structs) as values. - - - - - - - - - -
 I couldn't get the AA's to nest the way they do in Ruby, so
 I had to do it differently.
I will take a look at this later. Maybe it's a known AA bug. - - - - - - - - - -
 This task seemed like a good candidate for using an invariant,
 but the loop in the run method already checks the state on
 every iteration, so I'm not sure what you could check except
 to see if all the fields have been initialized perhaps.
Seems good to do, but maybe a pre-condition is enough. - - - - - - - - - - Instead of using toString() maybe it's better to add a printTape, and let run() return nothing. I have also converted UTM to a struct, because for this little program it doesn't need to be a class (and there is no need of new). - - - - - - - - - - I am not so fond of the D idiom of using general Exceptions, I'd like to use a bit more variety of Phobos-defined exceptions. But in this little program I think using two basic Exception is acceptable. - - - - - - - - - - The two casts in your code are bad, generally in D you don't cast to mutable or to immutable, because it's dangerous and unclean. So I will (try to) remove them: this(ref TuringMachine tm) { this.tm = cast(immutable)tm; this.head = TapeHead(this.tm); } void run() { if (this.halted) throw new Exception("Machine already halted."); auto state = cast()this.tm.initialState; - - - - - - - - - - Maybe later I'll write more comments. Bye, bearophile
Feb 15 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 Instead of using toString() maybe it's better to add a 
 printTape, and let run() return nothing. I have also converted 
 UTM to a struct, because for this little program it doesn't 
 need to be a class (and there is no need of new).
I meant the opposite, sorry: printTape() ==> toString() Bye, bearophile
Feb 15 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
A first revision, do you like the toString?

http://codepad.org/qhH2XpMx

- - - - - - - - - - -

The modified code contains still an enum that gets converted to 
char and then to int. I am not going to write code like that in 
my own "production code" :-)

- - - - - - - - - - -

To improve this type soup a bit I suggest to introduce one or 
more alias for the types of states, etc, like:

alias State = char;

and then use it/them.


static struct TuringMachine {
     char[] symbols;
     char blank;
     char initialState;
     char[] haltStates, runningStates;
     char[][string] rules;
     char[] input;
}

static struct TapeHead {
     const char[] symbols;
     const char blank;
     char[] tape;
     size_t index;
...

- - - - - - - - - - -

Bye,
bearophile
Feb 15 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 16-2-2013 3:34, bearophile wrote:
 A first revision, do you like the toString?

 http://codepad.org/qhH2XpMx
It's fine, but we need another write at the end of run otherwise the final state doesn't get written.
 The modified code contains still an enum that gets converted to char and then
to int.
I am not going to write code like that in my own "production code" :-)
 - - - - - - - - - - -

 To improve this type soup a bit I suggest to introduce one or more alias for
the types of states, etc, like:

 alias State = char;
Good idea. I'll change that. I'm still not happy with the TuringMachine creation although it looks more organized than before. I'm thinking about putting the definitions in xml, then have a parser create an immutable TuringMachine that we can then pass to UTM. That would also take care of the nested AA problem. The rules object can then have a tuple or a struct. BTW, the reason I used a class is that it forces you to instantiate through the constructor. If you use a class and write: (new UTM().run()); // fails at compile time If you use a struct and write: UTM().run(); // fails at runtime
Feb 16 2013
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 It's fine, but we need another write at the end of run 
 otherwise the final state doesn't get written.
OK. Feel free to fix the code: http://codepad.org/MvpSET1I Writing good enough code is an iterative process... And this code will probably need few more iterations.
 I'm thinking about putting the definitions in xml,
Please no :-) Especially in a such small program.
 BTW, the reason I used a class is that it forces you to 
 instantiate through the constructor.

 If you use a class and write:

 (new UTM().run()); // fails at compile time

 If you use a struct and write:

 UTM().run(); // fails at runtime
OK, feel free to change back the code to a final class. We'll try to find a better solution in successive iterations. Bye, bearophile
Feb 16 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 BTW, the reason I used a class is that it forces you to 
 instantiate through the constructor.
One possible solution: http://codepad.org/9PO8hpI7 Bye, bearophile
Feb 16 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 16-2-2013 14:04, bearophile wrote:
 Jos van Uden:

 BTW, the reason I used a class is that it forces you to instantiate through
the constructor.
One possible solution: http://codepad.org/9PO8hpI7
Initializing the struct that way didn't work because I changed the AA back to nested. This is what I have now (incorperated part of your suggestions): http://codepad.org/wjaSgppT
Feb 16 2013
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 This is what I have now (incorperated part of your suggestions):

 http://codepad.org/wjaSgppT
It looks good. It's not a strongly typed code (because states are just chars), and it's not much flexible because UTM is not templated on Symbol and State, but for this task it's OK. Some small changes: http://codepad.org/r4NkxTcn Before putting it in Rosettacode the UTM constructor needs a pre-condition that verifies the full correctness of all its inputs. Then do you want to put it in Rosettacode yourself? Bye, bearophile
Feb 16 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
By the way, with this little program I have found two new 
compiler bugs, I will put it in Bugzilla later.

Bye,
bearophile
Feb 16 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
 with this little program I have found two new compiler bugs, I 
 will put it in Bugzilla later.
http://d.puremagic.com/issues/show_bug.cgi?id=9520 http://d.puremagic.com/issues/show_bug.cgi?id=9521 Bye, bearophile
Feb 16 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
The version you have put in Rosettacode is good, I have just 
added some missing tests at the beginning of the UTM constructor.

Annotations like this are reminders of DMD bugs/limits that 
hopefully we'll be fixed/lifeted:
foreach (/*const*/ s, const rule; aa) {


While this annotation:
alias State = char; // Typedef?

means that in a stronger typed entry maybe State should be (but 
we have also to benchmark if this doesn't decrease the program 
performance for a successive bigger Busy Beaver machine):
alias State = Typedef!char;


This little program is pedagogically very good at showing the 
difference between weak and strong static typing. In a strongly 
static typed version all (or most) of those run-time tests are 
not needed.

Bye,
bearophile
Feb 16 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 16-2-2013 18:23, bearophile wrote:
 The version you have put in Rosettacode is good, I have just added some
missing tests at the beginning
  of the UTM constructor.
I added that precondition reluctantly, that's why its short :-). I really feel that input validation should be done elsewhere. I was thinking about adding a factory method to the UTM that accepts a string array, parses and validates it, and returns a fully initialized immutable TuringMachine. It would still be a lot of ugly code though. That stronger typing can reduce the need for input checking is something I find interesting. I'll have a look at the Ada code.
 (but we have also to benchmark if this doesn't decrease the program
performance for a
  successive bigger Busy Beaver machine):
On the other hand, if we have stronger typing we may not have to do the rather expensive checks that are currently in the loop.
Feb 16 2013
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 I added that precondition reluctantly, that's why its short 
 :-). I really feel that
 input validation should be done elsewhere.
A full validation needs to be done somewhere :-)
 I was thinking about adding a factory method to the UTM that 
 accepts a string array,
 parses and validates it, and returns a fully initialized 
 immutable TuringMachine.
 It would still be a lot of ugly code though.
Probably in D there are better solutions.
 That stronger typing can reduce the need for input checking is 
 something I find interesting.
It's interesting :-) A strong typing has some disadvantages (the code is more fussy, the program usually gets a little less easy to read and a little longer, etc.), but it has some advantages too. Languages like Ada, Haskell and ATS enjoy such strong typing to avoid many bugs and many run-time errors. In some Rosettacode Tasks I have put two different solutions, one less and one more strongly typed: http://rosettacode.org/wiki/Hidato#D http://rosettacode.org/wiki/Matrix_multiplication#D There are languages like ATS (http://www.ats-lang.org/ ) able to catch statically many problems otherwise found at run-time in lesser languages. Well written ATS programs are also fast as C programs, so there is no loss in performance. On the other hand writing ATS code is not easy.
 I'll have a look at the Ada code.
Ada code is very readable (far more than C++). But compared to D you have to write too much code.
 (but we have also to benchmark if this doesn't decrease the 
 program performance for a
 successive bigger Busy Beaver machine):
On the other hand, if we have stronger typing we may not have to do the rather expensive checks that are currently in the loop.
Right :-) Onward to the next Rosetta tasks :-) Bye, bearophile
Feb 16 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
There is a way to make the D code faster: prepending a cell in 
left() is a slow operation:

void right() pure nothrow {
     this.position++;
     if (this.position == this.tape.length)
         this.tape ~= this.blank;
}

void left() pure nothrow {
     if (this.position == 0)
         this.tape = this.blank ~ this.tape;
     else
         this.position--;
}


If you want to make the code faster (useful for a larger Busy 
Beaver simulation), you keep two tapes as two dynamic arrays. One 
tape represents the items on the right of the origin and the 
other tape on the left of the origin. So the position becomes a 
signed integer and both left() and right() use a fast append 
operation.

Bye,
bearophile
Feb 16 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 16-2-2013 19:55, bearophile wrote:
 There is a way to make the D code faster: prepending a cell in left() is a
slow operation:

 void right() pure nothrow {
      this.position++;
      if (this.position == this.tape.length)
          this.tape ~= this.blank;
 }

 void left() pure nothrow {
      if (this.position == 0)
          this.tape = this.blank ~ this.tape;
      else
          this.position--;
 }


 If you want to make the code faster (useful for a larger Busy Beaver
simulation), you keep two tapes as two dynamic arrays. One tape represents the
items on the right of the origin and the other tape on the left of the origin.
So the position becomes a signed integer and both left() and right() use a fast
append operation.
Yes, that was your original suggestion, but I didn't quite understand it, so I went with the Ruby solution. You would reverse the left array when printing, is that correct?
Feb 16 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 Yes, that was your original suggestion, but I didn't quite 
 understand it,
When you don't understand something I say, please ask for more info :-)
 You would reverse the left array when printing, is that correct?
Right, the second half of the tape keeps the cells in reverse order. Bye, bearophile
Feb 16 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 16-2-2013 21:23, bearophile wrote:
 Jos van Uden:

 Yes, that was your original suggestion, but I didn't quite understand it,
When you don't understand something I say, please ask for more info :-)
 You would reverse the left array when printing, is that correct?
Right, the second half of the tape keeps the cells in reverse order.
I've split the tape in left and right. It does make the code a bit harder to understand and debug. A linkedlist would have been more elegant, but slower I guess. The stress test that was posted on the talk page, I've also added. Our UTM produces the correct result but with redundant blanks on both sides. 0111111222222220 ^ http://codepad.org/2SK611Wd
Feb 17 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 I've split the tape in left and right. It does make the code a 
 bit harder to understand and debug.
You have used three tapes and a unsigned position, while I think a signed position and two tapes is enough: static struct TapeHead { immutable Symbol blank; Symbol[] tape, left, right; size_t position; The code becoming a little longer and a little less easy to understand was expected. But is it worth doing it for this Rosettacode Task? I think it's not worth making the code more complex. With the tm3 the new code prints the last two states: 0111111222222220 ^ 0111111222222220 ^ While the older code prints something different and probably more correct: 0111111222222220 ^ 0111111222222220 ^
 A linkedlist would have been more elegant, but slower I guess.
On modern CPUs 99% of the times linked lists are the wrong data structure to use. They have low data density and incur in high cache misses. Benchmarks shows that in some cases arrays need to be preferred even when deletions in the middle are not so common. Linked lists are better when you have to insert and remove many items randomly in the middle of the sequence and you don't have to transverse all the sequence often. This double condition is not so common.
 The stress test that was posted on the talk page, I've also 
 added.
Good. It's better to add it to the precedent version of the UTM.
 Our UTM produces the correct result but with redundant blanks on
 both sides.

 0111111222222220
  ^
A Turning Machine is supposed to have a tape that is infinite in both directions, so when you print the tape you trim the blanks away at both ends. So a better printing is: ...11111122222222... Or: Incrementer: ...111... ^ ...111... ^ ...111... ^ ...1110... ^ ...1111... ^ Bye, bearophile
Feb 17 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
 so when you print the tape you trim the blanks away at both 
 ends.
A wrong trimming code: string toString() const { // Blank-stripped tape. const t2 = tape .find!(c => c != blank)() .retro() .find!(c => c != blank)() .retro(); return format("...%(%)...", t2.empty ? [blank] : t2) ~ '\n' ~ format("%" ~ text(position + 4) ~ "s", "^") ~ '\n'; } It gives: Busy beaver machine (3-state, 2-symbol): ...0... ^ ...1... ^ The second line should show the cell up to the head position: Busy beaver machine (3-state, 2-symbol): ...0... ^ ...10... ^ There are many ways to improve this program, like trimming away the blanks correctly, but I think the code is acceptable now: http://rosettacode.org/wiki/Universal_Turing_machine#D Bye, bearophile
Feb 17 2013
prev sibling parent reply "SomeDude" <lovelydear mailmetrash.com> writes:
On Tuesday, 5 February 2013 at 20:10:37 UTC, bearophile wrote:
 Jos van Uden:

 I'll give it a shot if you like. The RCRPG I'd like to try 
 first.
I have already partially written those: Partial translation of rcrpg-Python: http://codepad.org/SflrKqbT Partial translation of permutations_rank_of_a_permutation-Python: http://codepad.org/El9SQwOE Plus a better Perl implementation of the uniform() on BigInts: http://codepad.org/LGcMpk2f Partial translation of the universal_turing_machine-Ruby: http://codepad.org/nUXLzAg2 Bye, bearophile
codepad.org doesn't work at all here. Maybe you should use dpaste (or pastebin for other languages) instead ?
Feb 09 2013
next sibling parent Jos van Uden <usenet fwend.com> writes:
On 9-2-2013 23:14, SomeDude wrote:
  
 codepad.org doesn't work at all here. Maybe you should use dpaste (or pastebin
for other languages) instead ?
It's not working for me either. It's probably a temporary problem. It worked fine before.
Feb 09 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
SomeDude:

...
 Partial translation of rcrpg-Python:
 http://codepad.org/SflrKqbT

 Partial translation of 
 permutations_rank_of_a_permutation-Python:
 http://codepad.org/El9SQwOE
 Plus a better Perl implementation of the uniform() on BigInts:
 http://codepad.org/LGcMpk2f

 Partial translation of the universal_turing_machine-Ruby:
 http://codepad.org/nUXLzAg2

 Bye,
 bearophile
codepad.org doesn't work at all here. Maybe you should use dpaste (or pastebin for other languages) instead ?
Links in the same order: http://dpaste.dzfl.pl/10eff346 http://dpaste.dzfl.pl/bfde8010 http://dpaste.dzfl.pl/3a172308 http://dpaste.dzfl.pl/22b7a931 Bye, bearophile
Feb 09 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 10-2-2013 1:57, bearophile wrote:
 ...
 Partial translation of rcrpg-Python:
 http://codepad.org/SflrKqbT
I have the rcrpg working, but I want to test it some more. I'm not very happy with the alias function, it accepts just about any input, it can put the program in an invalid state. There was a bug by the way in the Python code, that slowed me down a bit. As for the "getattr", I've hacked a CTFE loop together that writes out if statements. I'm not sure how robust it is. We can always go for a handwritten "if else" or switch block. http://dpaste.dzfl.pl/5e6b824e
Feb 11 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 I have the rcrpg working, but I want to test it some more.
Good. Adding a bit of unittesting is acceptable, I think.
 I'm not very happy
 with the alias function, it accepts just about any input, it 
 can put the program in an invalid state.
I presume this is a design bug shared with the original Python code. You have also fixed a translation bug of mine with remove(). I don't like that function. In past I did another mistake (in another program), forgetting to assign its result back to the array.
 There was a bug by the way in the Python code, that slowed me 
 down a bit.
D static type system asks for more coding work, but it has caught very quickly that bug of this line of Python code: tokens[0] = aliases[tokens[0]] Dynamic typing has some advantages and in some cases it's handy, but it has some disadvantages too. On the other hand I think that Python code was not well tested; Python unittesting is able to catch most of similar bugs. I think we should fix the Python entry too (or at least add a note in the Talk page).
 As for the "getattr", I've hacked a CTFE loop together that 
 writes out if statements. I'm not sure how robust it is.
I think in normal D code you don't catch Throwable, but maybe in this case it's OK.
 http://dpaste.dzfl.pl/5e6b824e
The D code has lot of imports because Python has a ton of built-in things. I have shortened the lines to about 72 chars max, and reformatted the code a bit. If you like it and you have a Rosettacode account, you can put it there yourself (otherwise I'll do it myself). If later you find bugs or you want to change something, there's always the possibility to modify it on the site. http://dpaste.dzfl.pl/6778053f In practice at the moment I am maintaining all the D entries of Rosettacode. I keep the coding style uniform, but sometimes I change some parts of such style on purpose to show different ways to use D, or specific things. Several Rosettacode solutions have more than one D entry, like when there is a very short and high-level entry and a longer and low level entry that's faster. Bye, bearophile
Feb 11 2013
parent reply "safety0ff" <safety0ff.dev gmail.com> writes:
On Tuesday, 12 February 2013 at 01:07:35 UTC, bearophile wrote:
 In practice at the moment I am maintaining all the D entries of 
 Rosettacode.
I modified the Hamming numbers code in a personal exercise. It now uses considerably less memory but is slower. I've posted the code here in case it is of use: http://dpaste.dzfl.pl/3990023e5577 For a single n, n = 350_000_000: Alternative version 2: 13.4s and ~5480 MB of ram My code: 21s and ~74 MB of ram Regards.
Jul 30 2014
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
safety0ff:

 I modified the Hamming numbers code in a personal exercise.
 It now uses considerably less memory but is slower.

 I've posted the code here in case it is of use: 
 http://dpaste.dzfl.pl/3990023e5577

 For a single n, n = 350_000_000:
 Alternative version 2: 13.4s and ~5480 MB of ram
 My code: 21s and ~74 MB of ram
I have added your version, with small changes and improvements. I suggest to not put attributes like this: static struct Candidate { typeof(Hamming.ln) ln; typeof(Hamming.e) e; pure nothrow: void increment(size_t n) { e[n] += 1; ln += lnprimes[n]; } const: bool opEquals(T)(in ref T y) { // return this.e == y.e; // slow return !((this.e[0] ^ y.e[0]) | (this.e[1] ^ y.e[1]) | (this.e[2] ^ y.e[2])); } int opCmp(T)(in ref T y) { return ln > y.ln ? 1 : (ln < y.ln ? -1 : 0); } } Bye, bearophile
Jul 31 2014
prev sibling parent reply "safety0ff" <safety0ff.dev gmail.com> writes:
On Tuesday, 12 February 2013 at 01:07:35 UTC, bearophile wrote:
 In practice at the moment I am maintaining all the D entries of 
 Rosettacode.
Here's a candidate for http://rosettacode.org/wiki/Extensible_prime_generator#D in case it is preferred to the existing entry: http://dpaste.dzfl.pl/43735da3f1d1
Aug 07 2014
parent "bearophile" <bearophileHUGS lycos.com> writes:
safety0ff:

 Here's a candidate for 
 http://rosettacode.org/wiki/Extensible_prime_generator#D in 
 case it is preferred to the existing entry:
 http://dpaste.dzfl.pl/43735da3f1d1
I was away. I have added your nice code with some small changes as an alternative faster version. I think you have compiled your code without -wi, so I have added a "goto default;" inside the third switch case of the sieveOne function. Bye, bearophile
Aug 14 2014
prev sibling parent reply Jos van Uden <usenet fwend.com> writes:
On 5-2-2013 20:45, Jos van Uden wrote:
  
 By the way, I think 'Qznc' may want to have a look at 'The dining
 philosophers':

 http://rosettacode.org/wiki/Dining_philosophers
Feb 15 2013
parent reply "qznc" <qznc go.to> writes:
On Saturday, 16 February 2013 at 02:23:42 UTC, Jos van Uden wrote:
 On 5-2-2013 20:45, Jos van Uden wrote:
 
 By the way, I think 'Qznc' may want to have a look at 'The 
 dining
 philosophers':

 http://rosettacode.org/wiki/Dining_philosophers
Am I the new rosetta concurency guy? :) I should find the time to solve it this weekend.
Feb 15 2013
parent reply "qznc" <qznc go.to> writes:
On Saturday, 16 February 2013 at 06:58:01 UTC, qznc wrote:
 On Saturday, 16 February 2013 at 02:23:42 UTC, Jos van Uden 
 wrote:
 On 5-2-2013 20:45, Jos van Uden wrote:
 
 By the way, I think 'Qznc' may want to have a look at 'The 
 dining
 philosophers':

 http://rosettacode.org/wiki/Dining_philosophers
I should find the time to solve it this weekend.
Wow, my kid let me do some hacking right now and it was simpler than expected. Posted a solution already.
Feb 15 2013
next sibling parent reply "monarch_dodra" <monarchdodra gmail.com> writes:
On Saturday, 16 February 2013 at 07:58:56 UTC, qznc wrote:
 On Saturday, 16 February 2013 at 06:58:01 UTC, qznc wrote:
 On Saturday, 16 February 2013 at 02:23:42 UTC, Jos van Uden 
 wrote:
 On 5-2-2013 20:45, Jos van Uden wrote:
 
 By the way, I think 'Qznc' may want to have a look at 'The 
 dining
 philosophers':

 http://rosettacode.org/wiki/Dining_philosophers
I should find the time to solve it this weekend.
Wow, my kid let me do some hacking right now and it was simpler than expected. Posted a solution already.
Hum... //---- Mutex[5] forks = new Mutex(); //---- This will allocate a single Mutex, and place the same reference in all five entries of forks. In a word: There is actually only one fork. The philosophers can still dine, because a single thread is allowed to lock the same resource twice, making the problem trivial. Basically, they are dual wielding the fork ;) The correct line of code should be: //---- Mutex[5] forks; foreach(ref fork; forks) fork = new Mutex(); //---- Or some variation thereof of course. The code still works with this change. I'm reporting it instead of correcting it directly, so as to better explain how and why.
Feb 16 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
monarch_dodra:

 I'm reporting it instead of correcting it directly, so as to 
 better explain how and why.
Thank you, some bugs are interesting. I will change the code. Bye, bearophile
Feb 16 2013
parent reply Jos van Uden <usenet fwend.com> writes:
The chirality of the given output on Langtons ant  doesn't match what
the code produces. (That's because somebody changed it a while ago).
See also the talk page.

http://rosettacode.org/wiki/Langton%27s_ant#D
Feb 19 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 The chirality of the given output on Langtons ant  doesn't 
 match what the code produces.
OK. I have changed the first entry. Bye, bearophile
Feb 19 2013
parent reply Jos van Uden <usenet fwend.com> writes:
Somebody added an incorrect notice to the D entry for Dijkstra's algorithm.
http://rosettacode.org/mw/index.php?title=Dijkstra%27s_algorithm&diff=next&oldid=147068
Feb 22 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 Somebody added an incorrect notice to the D entry for 
 Dijkstra's algorithm.
The task requires a directed graph: 1. Implement a version of Dijkstra's algorithm that computes a shortest path from a start vertex to an end vertex in a directed graph. So I have fixed the graph. Bye, bearophile
Feb 22 2013
prev sibling parent reply Jos van Uden <usenet fwend.com> writes:
On 16-2-2013 8:58, qznc wrote:
 On Saturday, 16 February 2013 at 06:58:01 UTC, qznc wrote:
 On Saturday, 16 February 2013 at 02:23:42 UTC, Jos van Uden wrote:
 On 5-2-2013 20:45, Jos van Uden wrote:

 By the way, I think 'Qznc' may want to have a look at 'The dining
 philosophers':

 http://rosettacode.org/wiki/Dining_philosophers
I should find the time to solve it this weekend.
Wow, my kid let me do some hacking right now and it was simpler than expected. Posted a solution already.
Wow, that was quick. Thanks!
Feb 16 2013
parent reply "Brian Rogoff" <brogoff gmail.com> writes:
On Saturday, 16 February 2013 at 11:30:00 UTC, Jos van Uden wrote:
 On 16-2-2013 8:58, qznc wrote:
 On Saturday, 16 February 2013 at 06:58:01 UTC, qznc wrote:
 On Saturday, 16 February 2013 at 02:23:42 UTC, Jos van Uden 
 wrote:
 On 5-2-2013 20:45, Jos van Uden wrote:

 By the way, I think 'Qznc' may want to have a look at 'The 
 dining
 philosophers':

 http://rosettacode.org/wiki/Dining_philosophers
I should find the time to solve it this weekend.
Wow, my kid let me do some hacking right now and it was simpler than expected. Posted a solution already.
Wow, that was quick. Thanks!
The current D code for Dining philosophers does not compile with dmd v2.063.2, the error message being dining.d(34): Error: cannot uniquely infer foreach argument types The code looks OK to me (but I'm a D newbie) so I wonder if someone could explain the inference issue. Where should an annotation be added to allow this to compile? 1 import std.stdio, std.algorithm, std.string, std.parallelism, 2 core.sync.mutex; 3 4 void eat(in uint i, in string name, Mutex[] forks) { 5 writeln(name, " is hungry."); 6 7 immutable j = (i + 1) % forks.length; 8 9 // Take forks i and j. The lower one first to prevent deadlock. 10 auto fork1 = forks[min(i, j)]; 11 auto fork2 = forks[max(i, j)]; 12 13 fork1.lock(); 14 scope(exit) fork1.unlock(); 15 16 fork2.lock(); 17 scope(exit) fork2.unlock(); 18 19 writeln(name, " is eating."); 20 writeln(name, " is full."); 21 } 22 23 void think(in string name) { 24 writeln(name, " is thinking."); 25 } 26 27 void main() { 28 const philosophers = "Aristotle Kant Spinoza Marx Russell".split(); 29 Mutex[philosophers.length] forks; 30 foreach (ref fork; forks) 31 fork = new Mutex(); 32 33 defaultPoolThreads = forks.length; 34 foreach (uint i, philo; taskPool.parallel(philosophers)) { 35 foreach (_; 0 .. 100) { 36 eat(i, philo, forks); 37 think(philo); 38 } 39 } 40 } BTW, I like the coding style being used in the rosetta examples and TDPL much better than the library style. -- Brian
Jun 22 2013
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Brian Rogoff:

 The current D code for Dining philosophers does not compile 
 with dmd v2.063.2, the error message being

 dining.d(34): Error: cannot uniquely infer foreach argument 
 types
I try to keep the D entries on Rosettacode updated, but every dmd release breaks tons of code, and Rosettacode has almost one thousand D programs (many tasks have two or more D entries, to show different solutions or different coding style, or to show code with different tradeoffs, etc), so you find some broken programs. I don't know what's changed in taskPool.parallel, I will investigate later. Or you can investigate yourself if you want.
 BTW, I like the coding style being used in the rosetta examples 
 and TDPL much better than the library style.
I try to keep the D code on Rosettacode with a quite uniform style. It follows the dstyle, the main difference is the opening brace that's in Egyptian style, but such brace style is required only in Phobos, while the dstyle does not require the Phobos style for all D code, it's in "Additional Requirements for Phobos": http://dlang.org/dstyle.html Later, bearophile
Jun 22 2013
prev sibling parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 06/22/2013 11:53 AM, Brian Rogoff wrote:

 The current D code for Dining philosophers does not compile with dmd
 v2.063.2, the error message being

 dining.d(34): Error: cannot uniquely infer foreach argument types
The code compiles under 32-bit (e.g. with the -m32 compiler switch) where size_t is an alias of uint.
       4    void eat(in uint i, in string name, Mutex[] forks) {
1) Replace that uint with size_t: void eat(in size_t i, in string name, Mutex[] forks) {
      34      foreach (uint i, philo; taskPool.parallel(philosophers)) {
2) Remove that uint: foreach (i, philo; taskPool.parallel(philosophers)) { Ali
Jun 22 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Ali Çehreli:

 The code compiles under 32-bit (e.g. with the -m32 compiler 
 switch) where size_t is an alias of uint.
Oh, I see. I compile most of the code on a 32 bit system. I asked Walter to warn d programmers against such mistakes, and Walter closed it down. Someone else has opened the ER again... Bye, bearophile
Jun 22 2013
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
 I asked Walter to warn d programmers against such mistakes, and 
 Walter closed it down. Someone else has opened the ER again...
I meant this: http://d.puremagic.com/issues/show_bug.cgi?id=5063 In the meantime I have fixed the Rosettacode entry. Bye, bearophile
Jun 22 2013
prev sibling next sibling parent "Brian Rogoff" <brogoff gmail.com> writes:
On Saturday, 22 June 2013 at 21:27:01 UTC, bearophile wrote:
 Ali Çehreli:

 The code compiles under 32-bit (e.g. with the -m32 compiler 
 switch) where size_t is an alias of uint.
Thanks, Ali! I'm always compiling on 64 bit systems; I'll add the 32 bit switch to my diagnostic approach now.
 Oh, I see. I compile most of the code on a 32 bit system.

 I asked Walter to warn d programmers against such mistakes, and 
 Walter closed it down. Someone else has opened the ER again...
In general, I think implicit conversions of any kind are a misfeature, but better error messages would be enough for me here. At least in Scala, you need to bring the conversion into scope yourself, or have it accidentally imported... Thanks for your help. -- Brian
Jun 23 2013
prev sibling parent Marco Leise <Marco.Leise gmx.de> writes:
Am Sat, 22 Jun 2013 23:27:00 +0200
schrieb "bearophile" <bearophileHUGS lycos.com>:

 Ali =C3=87ehreli:
=20
 The code compiles under 32-bit (e.g. with the -m32 compiler=20
 switch) where size_t is an alias of uint.
=20 Oh, I see. I compile most of the code on a 32 bit system. =20 I asked Walter to warn d programmers against such mistakes, and=20 Walter closed it down. Someone else has opened the ER again...
That would be me. Let's see where it goes. =20
 Bye,
 bearophile
--=20 Marco
Jul 03 2013
prev sibling next sibling parent reply "ixid" <nuaccount gmail.com> writes:
On Monday, 4 February 2013 at 23:55:25 UTC, bearophile wrote:
 Is the Fwend user of Rosettacode (or some other interested 
 person) around here? I have written partial D implementations 
 for three tasks, maybe a little of coordination will speedup 
 the work:

 http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
 http://rosettacode.org/wiki/Universal_Turing_machine
 http://rosettacode.org/wiki/RCRPG

 Bye,
 bearophile
If you're posting code on Rosetta code you are presenting that code as idiomatic. Doesn't that require some discussion of what is idiomatic D? You tend to use the superfluous parens which the properties discussion would suggest are becoming more idiomatic not to use. You also use 'in' a lot in function inputs while others have argued against it. This is not an attack on your code at all, but maybe there should be some discussion of and consensus on what is idiomatic.
Feb 12 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
ixid:

 If you're posting code on Rosetta code you are presenting that 
 code as idiomatic.
The D code on Rosettacode has some stylistic uniformity, and I think in most cases it follows the dstyle (http://dlang.org/dstyle.html ), but that code is not meant to be "production code" (lot of people in other languages don't add unittests, etc). So it is not idiomatic, and it's not meant to be. If you go on Rosettacode you can't expect to see code similar to Phobos code. There is also variability: some D entries of Rosettacode have unittests and are written in a readable style, other entries try to be short simple, and other entries are very strongly typed and longer, other entries look almost as C, and so on. This is done on purpose, to show various kinds of D coding. None of those ways is the only idiomatic one.
 You tend to use the superfluous parens which the properties 
 discussion would suggest are becoming more idiomatic not to use.
-property was supposed to become the standard semantics of the D language. So I have written code that way. Later things are changing. Now I am waiting to see what's coming out of the property discussion. If the final decision is that those parentheses aren't needed nor idiomatic, I/we will (slowly) remove the parentheses from the entries.
 You also use 'in' a lot in function inputs while others have 
 argued against it.
"in" is currently not good if you are writing a long term large library, or a larger program you want to use for lot of time, etc, because it assumes some type system semantics that is not yet implemented. But for the purposes of Rosettacode using "in" is good, because it's short, readable, and if/when scope will break some entries, I/we will fix them.
 This is not an attack on your code at all, but maybe there 
 should be some discussion of and consensus on what is idiomatic.
One problem of Rosettacode is that it's not so good to discuss. GitHub offers better means to discuss on the code. What other things do you want to discuss about? Bye, bearophile
Feb 12 2013
parent reply "ixid" <nuaccount gmail.com> writes:
 What other things do you want to discuss about?
I mean some level of D community discussion of the language as a whole as to what is an idiomatic style, perhaps after the current issues are settled, not anything specific about your code. There are areas like complex UFCS statements where it would help to have agreed, suggested ways of formatting.
Feb 12 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
ixid:

 I mean some level of D community discussion of the language as 
 a whole as to what is an idiomatic style, perhaps after the 
 current issues are settled, not anything specific about your 
 code.
Such discussion seems better in the main D newsgroup. But it also seems a good way to waste time with hundreds of posts that produce nothing of value :-)
 There are areas like complex UFCS statements where it would 
 help to have agreed, suggested ways of formatting.
I think this is currently a good way to format that kind of auto r = fooSomething() .barSomething!pred1() .bazSomething() .spamSomething!fun2(); In some cases on Rosettacode I have followed that formatting pattern. Bye, bearophile
Feb 12 2013
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
If some of you has a little of time to review code, I have 
converted the very fast C memory mapped version of "Ordered 
words" to D:

http://rosettacode.org/wiki/Ordered_words#Mmap

http://rosettacode.org/wiki/Ordered_words#Memory_Mapped_Version

The C version contains several pointers that get juggled around, 
even with a negative index:

if (s[0] < s[-1]) r = 0;

So the C entry is rather bug-prone (and it doesn't compile on GCC 
Windows). The D entry is portable, and uses mostly slices and 
(non-negative) array indexes.


The D findWord function is fiddly still:

const(char)[] findWord(const char[] s) pure nothrow  safe {
     size_t wordEnd = 0;
     while (wordEnd < s.length && s[wordEnd] != '\n'
            && s[wordEnd] != '\r')
         wordEnd++;
     return s[0 .. wordEnd];
}


I think a takeWhile (similar to a Python itertools function) is 
able to replace it:

return s.takeWhile!(c => !"\n\r".canFind(c));


Using the current Phobos (but a benchmark shows with DMD it's 
slower):

const(char)[] findWord(const char[] s) pure /*nothrow*/  safe {
     immutable wordEnd = s.countUntil!q{a == '\n' || a == '\r'}();
     return s[0 .. wordEnd >= 0 ? wordEnd : $];
}

Bye,
bearophile
Feb 13 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
You have recently added:

http://rosettacode.org/wiki/Parse_command-line_arguments#D
http://rosettacode.org/wiki/Old_Russian_measure_of_length#D
http://rosettacode.org/wiki/Truth_table#D

But maybe there is one more Task you have recently added that I 
have missed.

Bye,
bearophile
Feb 25 2013
next sibling parent Jos van Uden <usenet fwend.com> writes:
On 25-2-2013 22:54, bearophile wrote:
 You have recently added:

 http://rosettacode.org/wiki/Parse_command-line_arguments#D
 http://rosettacode.org/wiki/Old_Russian_measure_of_length#D
 http://rosettacode.org/wiki/Truth_table#D
Yes.
 But maybe there is one more Task you have recently added that I have missed.
You can always click on "contribs" to get a better overview.
Feb 25 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 http://rosettacode.org/wiki/Truth_table#D
Some changes: http://codepad.org/PEZWmrHG But it's not good enough yet :-) Maybe there are ways to produce a D version closed to the Go one. Bye, bearophile
Feb 25 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 26-2-2013 5:19, bearophile wrote:
 http://rosettacode.org/wiki/Truth_table#D
Some changes: http://codepad.org/PEZWmrHG But it's not good enough yet :-) Maybe there are ways to produce a D version closed to the Go one.
I would have prefered to write: bool xor(in bool A, in bool B) pure nothrow return A != B; } But I couldn't figure out how to expand the boolean array to an argument list. The Go example uses runtime reflection, I believe. Nice touch with the map, I still think in loops :)
Feb 25 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 But I couldn't figure out how to expand the boolean array to
 an argument list.
I wrote a version, it's more statically type safe, but the code is quite hairy, and the foreach(i) generates too many templates if the predicate has many bool arguments: http://codepad.org/9Ar1pmMc Are you able to improve it?
 The Go example uses runtime reflection, I believe.
I'd like a bit more reflection in D, to avoid a similar jungle of templates :-) I think Rosettacode is currently down. Bye, bearophile
Feb 26 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 But I couldn't figure out how to expand the boolean array to
 an argument list.
With functions like this my last version will become simpler, and it's equally statically type safe: bool xor(in bool[2] args) pure nothrow { return b[0] != b[1]; } Bye, bearophile
Feb 26 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 With functions like this my last version will become simpler, 
 and it's equally statically type safe:

 bool xor(in bool[2] args) pure nothrow {
     return b[0] != b[1];
 }
This third version is much simpler and it seems good enough for Rosettacode: http://codepad.org/YJjb1t91 Bye, bearophile
Feb 26 2013
next sibling parent "Jos van Uden" <usernet fwend.com> writes:
On Tuesday, 26 February 2013 at 14:10:04 UTC, bearophile wrote:
 With functions like this my last version will become simpler, 
 and it's equally statically type safe:

 bool xor(in bool[2] args) pure nothrow {
    return b[0] != b[1];
 }
This third version is much simpler and it seems good enough for Rosettacode: http://codepad.org/YJjb1t91
Yes, it's much nicer than the heavily templated one. We may be able to update it if/when std.reflection comes through. I'd prefer the more conventional notation (i & (1 << j)) != 0, rather than the double negative.
Feb 26 2013
prev sibling parent reply FG <home fgda.pl> writes:
On 2013-02-26 15:10, bearophile wrote:
 This third version is much simpler and it seems good enough for
 Rosettacode:

 http://codepad.org/YJjb1t91
Nice. Myself I'd add bits.reverse; after the N.iota.map..., because I'm more used to a truth table where the left-most operands iterate the slowest.
Feb 27 2013
parent reply FG <home fgda.pl> writes:
On 2013-02-27 12:47, FG wrote:
 On 2013-02-26 15:10, bearophile wrote:
 This third version is much simpler and it seems good enough for
 Rosettacode:

 http://codepad.org/YJjb1t91
Nice. Myself I'd add bits.reverse; after the N.iota.map..., because I'm more used to a truth table where the left-most operands iterate the slowest.
or, without reverse, but perhaps not very clear: N.iota.map!(j => !!(i & (1 << (N - j - 1)))).copy(bits[]);
Feb 27 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
FG:

 or, without reverse, but perhaps not very clear:
 N.iota.map!(j => !!(i & (1 << (N - j - 1)))).copy(bits[]);
OK, improved in Rosettacode. Bye, bearophile
Feb 27 2013
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
A possible idea is to translate this last Python version to D:

http://rosettacode.org/wiki/Hamming_numbers#Cyclic_generator_method_.232.

- - - - - - - - - - - -

Another idea is to add a D version of Merge Sort that works with 
just a Input Range (like a single linked list, as a SList):
http://rosettacode.org/wiki/Merge_sort

Slicing the input range in two is probably possible. But what's 
the result of such function? Just an array created with an 
Appender? It can't be the same type of the input, because it is 
just a input range, so it doesn't need to have a put(). Maybe a 
given sink that is an output range? Or maybe a sink created 
inside given its type as template argument?

Bye,
bearophile
Feb 27 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Now and then this thread becomes very useful for some 
coordination and discussion.

Regarding this Task:
http://rosettacode.org/wiki/Take_notes_on_the_command_line#D

Fwend has recently modified it with this note:

the file only needs to be created before append; filename can be 
written as one word in English, no need for camel case)<
Sorry, I didn't know "filename" a single English word :-) http://dictionary.cambridge.org/dictionary/business-english/filename?q=filename Regarding the other problem, the last part of the Task says:
If NOTES.TXT doesn't already exist in the current directory then 
a new NOTES.TXT file should be created.<
If no text file exists in the directory and I run the current program with no arguments, it generates no file to me. So I think the current program is wrong. That's why I added a File(fileName, "w");. What do you think? Bye, bearophile
Mar 04 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 4-3-2013 23:04, bearophile wrote:
 Now and then this thread becomes very useful for some coordination and
discussion.

 Regarding this Task:
 http://rosettacode.org/wiki/Take_notes_on_the_command_line#D

 Fwend has recently modified it with this note:

 the file only needs to be created before append; filename can be written as
one word in English, no need for camel case)<
Sorry, I didn't know "filename" a single English word :-) http://dictionary.cambridge.org/dictionary/business-english/filename?q=filename Regarding the other problem, the last part of the Task says:
 If NOTES.TXT doesn't already exist in the current directory then a new
NOTES.TXT file should be created.<
If no text file exists in the directory and I run the current program with no arguments, it generates no file to me. So I think the current program is wrong. That's why I added a File(fileName, "w");. What do you think?
It depends on how you interpret it. The task describes two actions: display and append. The question is: does the last sentence refer to the append action or to both display and append. I choose to think it refers to the append action because that makes more sense. As for http://rosettacode.org/wiki/Simple_database You removed the struct that I used to encapsulate the functions. Aren't these functions now exposed to other modules? I wanted them to only be callable from main. The input validation relies on that. At first I had declared them all private, but then I thought it would be convenient to put a struct around them and declare it private. Maybe there's a better way.
Mar 04 2013
next sibling parent reply Jos van Uden <usenet fwend.com> writes:
On 5-3-2013 0:57, Jos van Uden wrote:
 On 4-3-2013 23:04, bearophile wrote:
 Now and then this thread becomes very useful for some coordination and
discussion.

 Regarding this Task:
 http://rosettacode.org/wiki/Take_notes_on_the_command_line#D

 Fwend has recently modified it with this note:

 the file only needs to be created before append; filename can be written as
one word in English, no need for camel case)<
Sorry, I didn't know "filename" a single English word :-) http://dictionary.cambridge.org/dictionary/business-english/filename?q=filename Regarding the other problem, the last part of the Task says:
 If NOTES.TXT doesn't already exist in the current directory then a new
NOTES.TXT file should be created.<
If no text file exists in the directory and I run the current program with no arguments, it generates no file to me. So I think the current program is wrong. That's why I added a File(fileName, "w");. What do you think?
It depends on how you interpret it. The task describes two actions: display and append. The question is: does the last sentence refer to the append action or to both display and append. I choose to think it refers to the append action because that makes more sense. As for http://rosettacode.org/wiki/Simple_database You removed the struct that I used to encapsulate the functions. Aren't these functions now exposed to other modules? I wanted them to only be callable from main. The input validation relies on that. At first I had declared them all private, but then I thought it would be convenient to put a struct around them and declare it private. Maybe there's a better way.
Another consideration, I just remembered, was that it avoided creating global variables.
Mar 04 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 Another consideration, I just remembered, was that it avoided
 creating global variables.
Right, that's important, but every rule should be followed with a grain of salt. First of all in this program there are no global variables, just a global immutable, filename. Global immutables cause far less troubles than global variables. (In my opinion hard-coding the file name like that is not nice, but for this little program it's acceptable). And second, this is a very small program. What's bad in a 100_000 lines long program is sometimes acceptable in a 73 cloc lines long program... Bye, bearophile
Mar 04 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 It depends on how you interpret it. The task describes two 
 actions:
 display and append. The question is: does the last sentence 
 refer to
 the append action or to both display and append. I choose to 
 think it
 refers to the append action because that makes more sense.
OK. - - - - - - - - - - - -
 As for http://rosettacode.org/wiki/Simple_database

 You removed the struct that I used to encapsulate the functions.

 Aren't these functions now exposed to other modules? I wanted
 them to only be callable from main. The input validation relies
 on that.

 At first I had declared them all private, but then I thought it
 would be convenient to put a struct around them and declare it
 private. Maybe there's a better way.
D isn't a pure OOP language, it thankfully supports free functions. Generally structs and classes shouldn't be used if they are not useful (this is well known in the Python community). A struct with just static methods is essentially a namespace. In D modules are namespaces, so there is less need to wrap static functions in a struct. In this case of the Simple database Task I think this is not a module to be imported, because it has a main. It's a complete program (like other hundreds of D Tasks in Rosettacode) and it's not meant to be imported. So I think wrapping everything in a struct in this case is useless, it just increases the indenting. Do you agree? - - - - - - - - - - - - Extra note: in Rosettacode there are also few tasks meant as modules to be imported and used. They have the main wrapped like this: version (task_name_main) { void main() { } } Unfortunately in D there is no built-in way to make a module that has a main() when it's compiled as "main module" (or when it's compiled as stand alone) and masks its main() when it's imported by another module. This is done in Python with the "if __name__ == __main__:" idiom. Some people say that a similar idiom is ugly, but it's far better to have such not nice looking but standard idiom, than having nothing and using a nonstandard version() like that. Bye, bearophile
Mar 04 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 5-3-2013 1:20, bearophile wrote:
 Jos van Uden:

 It depends on how you interpret it. The task describes two actions:
 display and append. The question is: does the last sentence refer to
 the append action or to both display and append. I choose to think it
 refers to the append action because that makes more sense.
OK. - - - - - - - - - - - -
 As for http://rosettacode.org/wiki/Simple_database

 You removed the struct that I used to encapsulate the functions.

 Aren't these functions now exposed to other modules? I wanted
 them to only be callable from main. The input validation relies
 on that.

 At first I had declared them all private, but then I thought it
 would be convenient to put a struct around them and declare it
 private. Maybe there's a better way.
D isn't a pure OOP language, it thankfully supports free functions. Generally structs and classes shouldn't be used if they are not useful (this is well known in the Python community). A struct with just static methods is essentially a namespace. In D modules are namespaces, so there is less need to wrap static functions in a struct. In this case of the Simple database Task I think this is not a module to be imported, because it has a main. It's a complete program (like other hundreds of D Tasks in Rosettacode) and it's not meant to be imported. So I think wrapping everything in a struct in this case is useless, it just increases the indenting. Do you agree?
I'm not attached to the struct, but it doesn't feel right to have these functions publicly accessible. It's a matter of good coding practice. If I import a module these functions are exposed.
Mar 04 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 but it doesn't feel right to have these
 functions publicly accessible. It's a matter of good coding 
 practice.

 If I import a module these functions are exposed.
I think you can't import this module, because it has a main(). But if you fear that, then I've added "private" to all global identifiers: http://rosettacode.org/wiki/Simple_database#D Bye, bearophile
Mar 04 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 But if you fear that, then I've added "private" to all global 
 identifiers:
 http://rosettacode.org/wiki/Simple_database#D
I have removed "private" again, because it's bad to program compromises. This is a complete program, it's not a module, and it's not imported. No need for private things. Bye, bearophile
Mar 04 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 5-3-2013 2:05, bearophile wrote:
 But if you fear that, then I've added "private" to all global identifiers:
 http://rosettacode.org/wiki/Simple_database#D
I have removed "private" again, because it's bad to program compromises. This is a complete program, it's not a module, and it's not imported. No need for private things.
// this shouldn't happen test.d import simdb; void fun() { auto db = load(); // etc store(db); }
Mar 05 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 5-3-2013 11:45, Jos van Uden wrote:
 On 5-3-2013 2:05, bearophile wrote:
 But if you fear that, then I've added "private" to all global identifiers:
 http://rosettacode.org/wiki/Simple_database#D
I have removed "private" again, because it's bad to program compromises. This is a complete program, it's not a module, and it's not imported. No need for private things.
// this shouldn't happen test.d import simdb; void fun() { auto db = load(); // etc store(db); }
That can't happen. I really mean: test.d void fun() { auto db = load(); // etc store(db); } simdb.d import test; fun();
Mar 05 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 // this shouldn't happen

 test.d

 import simdb;
If I try to compile something like that my dmd gives me a duplicated main error, or something similar.
 I really mean:

 test.d
  void fun() {
      auto db = load();
      // etc
      store(db);
 }

 simdb.d

 import test;

 fun();
Do you mean that the load and store functions are "private" and should only be called by other functions in the module? (If this is true, then it's enough to mark as module-private those two functions). Bye, bearophile
Mar 05 2013
parent "Jos van Uden" <usenet fwend.com> writes:
On Tuesday, 5 March 2013 at 13:12:49 UTC, bearophile wrote:
 Jos van Uden:

 // this shouldn't happen

 test.d

 import simdb;
If I try to compile something like that my dmd gives me a duplicated main error, or something similar.
Sorry, that was a wrong example.
 I really mean:

 test.d
 void fun() {
     auto db = load();
     // etc
     store(db);
 }

 simdb.d

 import test;

 fun();
Do you mean that the load and store functions are "private" and should only be called by other functions in the module? (If this is true, then it's enough to mark as module-private those two functions).
Yes, but I think it would be best to put a private modifier around the entire code, except main. private { ... }
Mar 05 2013
prev sibling next sibling parent reply "ixid" <nuaccount gmail.com> writes:
I was just looking at the Rosetta code for prime decomposition 
and it seems bugged to me, wanted to make sure as you seem to be 
the one coordinating these things:

http://rosettacode.org/wiki/Prime_decomposition#D

This will potentially return a 1 in the list of primes which is a 
bug as 1 isn't prime.
Mar 19 2013
next sibling parent reply "Andrea Fontana" <nospam example.com> writes:
On Tuesday, 19 March 2013 at 15:55:19 UTC, ixid wrote:
 I was just looking at the Rosetta code for prime decomposition 
 and it seems bugged to me, wanted to make sure as you seem to 
 be the one coordinating these things:

 http://rosettacode.org/wiki/Prime_decomposition#D

 This will potentially return a 1 in the list of primes which is 
 a bug as 1 isn't prime.
You're right. I think the right code for decompose is this: T[] decompose(T)(T n) /*pure nothrow*/ { T[] res; for (T i = 2; n % i == 0;) { res ~= i; n /= i; } for (T i = 3; n != 1; i += 2) { // ----- Changed condition while (n % i == 0) { res ~= i; n /= i; } } // ----- Removed concat here return res; }
Mar 19 2013
parent "ixid" <nuaccount gmail.com> writes:
On Tuesday, 19 March 2013 at 16:47:43 UTC, Andrea Fontana wrote:
 On Tuesday, 19 March 2013 at 15:55:19 UTC, ixid wrote:
 I was just looking at the Rosetta code for prime decomposition 
 and it seems bugged to me, wanted to make sure as you seem to 
 be the one coordinating these things:

 http://rosettacode.org/wiki/Prime_decomposition#D

 This will potentially return a 1 in the list of primes which 
 is a bug as 1 isn't prime.
You're right. I think the right code for decompose is this: T[] decompose(T)(T n) /*pure nothrow*/ { T[] res; for (T i = 2; n % i == 0;) { res ~= i; n /= i; } for (T i = 3; n != 1; i += 2) { // ----- Changed condition while (n % i == 0) { res ~= i; n /= i; } } // ----- Removed concat here return res; }
T[] primeDecomposition2(T)(T n) /*pure nothrow*/ { T[] res; for (T i = 2; n % i == 0;) { res ~= i; n /= i; } for (T i = 3; n >= i * i; i += 2) { while (n % i == 0) { res ~= i; n /= i; } } if(n != 1) res ~= n; return res; } I think this is quite a lot faster, otherwise for numbers that are the products of a small and larger prime it will waste a lot of time reaching the larger prime's value.
Mar 19 2013
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
ixid:

 http://rosettacode.org/wiki/Prime_decomposition#D

 This will potentially return a 1 in the list of primes which is 
 a bug as 1 isn't prime.
From Python code, hopefully more correct and much faster: http://codepad.org/N4A7kxE1 Bye, bearophile
Mar 19 2013
parent reply "ixid" <nuaccount gmail.com> writes:
On Tuesday, 19 March 2013 at 17:18:01 UTC, bearophile wrote:
 ixid:

 http://rosettacode.org/wiki/Prime_decomposition#D

 This will potentially return a 1 in the list of primes which 
 is a bug as 1 isn't prime.
From Python code, hopefully more correct and much faster: http://codepad.org/N4A7kxE1 Bye, bearophile
This method seems to be a lot slower than just adding an if statement while giving the same answers (after sorting). For me it took 1.5 seconds to decompose 2 to 100,000 compared to 150ms for the method I posted above. Can you find an error in my method or shall I post that? I'll add a cast(T) 1 to the if statement so it can deal with big ints too.
Mar 19 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
ixid:

 Can you find an error in my method or shall I post that?
Small changes on your version: http://codepad.org/E9KHKvAi
 I'll add a cast(T) 1 to the if statement so
 it can deal with big ints too.
There's no need for that. Bye, bearophile
Mar 19 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 Small changes on your version:
 http://codepad.org/E9KHKvAi
It's now on Rosettacode. I have added more changes to make it able to deal with immutable input. Bye, bearophile
Mar 19 2013
parent reply "ixid" <nuaccount gmail.com> writes:
On Tuesday, 19 March 2013 at 18:53:21 UTC, bearophile wrote:
 Small changes on your version:
 http://codepad.org/E9KHKvAi
It's now on Rosettacode. I have added more changes to make it able to deal with immutable input. Bye, bearophile
Another issue to consider as the question I was attempting ended up requiring this, I wasn't aware of it when I made the original post: The prime factorization of 1 is an empty set, so surely to be correct it should return [] when given 1 and not throw an exception. This also suggests a possible modification to [].reduce!"a * b" as mathematically the product of the empty set is defined as 1.
Mar 20 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
ixid:

 The prime factorization of 1 is an empty set, so surely to be 
 correct it should return [] when given 1 and not throw an 
 exception.
The Task says that the input can't be 1, so the input 1 needs to be a pre-condition violation:
Write a function which returns an array or collection which 
contains the prime decomposition of a given number, n, greater 
than 1<
 This also suggests a possible modification to [].reduce!"a * b" 
 as mathematically the product of the empty set is defined as 1.
reduce() is a general function, so it's not supposed to know that. Python reduce does the same:
 reduce(lambda a, b: a * b, [])
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: reduce() of empty sequence with no initial value If you want that, then you have to use: reduce!"a * b"(1, items) And some time from now: items.reduce!"a * b"(1) If we add a product() function to Phobos similar to sum() (http://d.puremagic.com/issues/show_bug.cgi?id=4725 ) then I agree that for empty ranges it will need to return the multiplicative identity element. Bye, bearophile
Mar 20 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Some comments about the recently created "Vampire number" task in 
Rosettacode:

The version I have modified:
http://rosettacode.org/mw/index.php?title=Vampire_number&diff=154069&oldid=154068


Fwend has reverted most of my changes:
http://rosettacode.org/wiki/Vampire_number#D

------------

The rationale for some of my changes:

- main at the bottom. Giving a predicable order to the parts of 
the program is good. This how all the other entries are made.
- Removal of "if (auto factors = ...)": coding standards suggest 
to avoid mixing conditional tests with actions. Keeping code more 
tidy is safer.
- Removal of complex for loops "for (long n, count; n < long.max 
&& count < 25; n++)": it's better to keep the loop semantics 
simpler. It's better for both the optimization and for the 
readability and keeping the code in time.
- Adding immutable/const to the foreach loop variable "foreach 
(n; [...])": D currently gives a warning if you try to mutate it. 
In future D will allow you to mutate it, but it's only a copy, as 
in Python. This is potentially confusion. Marking it as 
const/immutable should become a standard D coding convention to 
avoid troubles. It's not useless.
- "immutable q = k / i;" instead of "long q = k / i;" all 
variables in a D program that don't need to mutate should be 
annotated with const/immutable. This gives more optimization to 
the compiler, helps avoid bugs of unwanted mutation later, and 
makes code simpler to understand, because when you read code you 
are sure something is not changing. It's explained here, among 
other places: 
http://blog.knatten.org/2011/11/11/disempower-every-variable/
- "if (digits.length % 2)" instead of "if (digits.length & 1)": 
for the compiler they are exactly the same, because the value is 
unsigned. And using a modulus is more clear here. We are 
discussing about parity, not about bits.
- "immutable f1 = getDigits(pair[0]);" instead of "auto f1 = 
getDigits(pair[0]);": as before, f1 doesn't need to change, so it 
should be immutable (I have used const, but immutable is better, 
because getDigits is now pure).
- Annotations like "pairs ~= [i, q]; // Heap-allocated pair.": 
they are useful because that little 2 items array is allocated on 
the heap. It's good to remember us an important inefficiency in 
the code. If you use a 2-tuple such inefficiency vanishes. 
Someday hopefully this significant inefficiency of array literals 
will be removed, and the comment will be removed.
- "// Unnecessary cast. Array concat allocates a new array." + 
"if (!(cast(long[])(f1 ~ f2)).sort().equal(digits))" instead of " 
if(!equal(digits, (f1 ~ f2).sort()))": f1 and f2 are immutable, 
and currently if you concatenate them you get an immutable array, 
that you can't sort. I agree the cast is bad here, so I have to 
use dup instead. In future this problem will be hopefully 
removed, so the code will be fixed and the comment removed. 
RosettaCode is not just a show of D code, it's also a place to 
help us improve D language itself. So hundreds of D entries in 
Rosettacode have annotations like that, that help us remember 
limits or bugs or problems in the D language. I have removed tens 
of similar annotations when D bugs get fixed. They are useful for 
the development od D.


(Here I have listed only the things that I think should be 
reverted. There are other things in my version of the problem 
that are more like personal style preferences that I have not 
listed here, that are used in most or all the other D entries.)

Bye,
bearophile
Mar 24 2013
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 - Removal of "if (auto factors = ...)": coding standards 
 suggest to avoid mixing conditional tests with actions. Keeping 
 code more tidy is safer.
Also in D testing array emptiness like that is generally dangerous. The idiomatic and correct way to do it in D is to use empty. Because in general arrays with zero length can be true: Another thing: the problem asks to return the results for 16758243290880, 24959017348650, 14593825548650, while your version of the program doesn't even show the last numbers. This is bad. The Python entry shows all three of them. Bye, bearophile
Mar 24 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
A new version of "Vampire number", do you like it?

http://codepad.org/DaVxWpoA

Bye,
bearophile
Mar 24 2013
prev sibling parent reply Jos van Uden <usenet fwend.com> writes:
On 24-3-2013 21:02, bearophile wrote:
 Some comments about the recently created "Vampire number" task in Rosettacode:

 The version I have modified:
 http://rosettacode.org/mw/index.php?title=Vampire_number&diff=154069&oldid=154068


 Fwend has reverted most of my changes:
 http://rosettacode.org/wiki/Vampire_number#D

 ------------

 The rationale for some of my changes:

 - main at the bottom. Giving a predicable order to the parts of the program is
good.
Either way is fine with me.
  This how all the other entries are made.
 - Removal of "if (auto factors = ...)": coding standards suggest to avoid
mixing conditional tests with actions. Keeping code more tidy is safer.
I think it's convenient, it checks for null or empty, I don't find it confusing at all.
 - Removal of complex for loops "for (long n, count; n < long.max && count <
25; n++)": it's better to keep the loop semantics simpler.
 It's better for both the optimization and for the readability and keeping the
code in time.
I agree that complex for loops should be avoided. I don't think this loop is complex though, it's very simple. (...) With regards to immutablity: I do find it useful, but it creates an anormous amount of code clutter. So I use it only where it's really important. For instance we have f1 and f2, they are declared const, and then only two lines later the constness has to be cast away again. I find that a bit over the top.
 - "if (digits.length % 2)" instead of "if (digits.length & 1)": for the
compiler they are exactly the same, because
  the value is unsigned. And using a modulus is more clear here. We are
discussing about parity, not about bits.
That is a matter of opinion. If I see "% 2", my first thought is: we're checking for even... then I realize the "== 0" is missing.
 - Annotations like "pairs ~= [i, q]; // Heap-allocated pair.":
The annotation got accidentally deleted, sorry.
 Another thing: the problem asks to return the results for 16758243290880,
24959017348650, 14593825548650,
while your version of the program doesn't even show the last numbers. This is
bad. The Python entry shows
all three of them.
Actually the task says: "Check if the following numbers are Vampire numbers and, if so, print them and their fangs". So you should only print it, if it is a Vampire number. I wrote the task myself, so I should know.
 A new version of "Vampire number", do you like it?
 http://codepad.org/DaVxWpoA
It's fine with me. I'm glad we got rid of the ugly cast.
Mar 24 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 I think it's convenient, it checks for null or empty, I don't 
 find it confusing at all.
I agree it's shorter and it looks handy. But one of its problems is that in D there are arrays with length zero that aren't null: import std.stdio; int[] foo() { auto a = [1]; return a[0..0]; } void main() { if (auto data = foo()) { writeln("here"); } } In the vampire code this doesn't happen because you return null (that is represented by two zero words), but in general unlike Python in D the safe and idiomatic way to test for array emptiness is to use std.array.empty. Otherwise you risk having problems.
 With regards to immutablity: I do find it useful, but it 
 creates an anormous amount of
 code clutter. So I use it only where it's really important. For 
 instance we have f1 and
 f2, they are declared const, and then only two lines later the 
 constness has to be cast
 away again. I find that a bit over the top.
f1 and f2 can be declared immutable, because they don't need to change. The later cast was a mistake of mine, I am sorry. In real-world D code in a situation like that I do as you have done, making f1 and f2 mutable. But on Rosettacode I think it's important to underline the current problems in the D language itself. In an hypothetical future version of D if you cancat two immutable arrays you should get something that is typed as immutable, but is implicitly castable to mutable :-) I will think a bit more about this. Maybe I will just make f1 and f2 mutable, it's the cleanest solution.
 - "if (digits.length % 2)" instead of "if (digits.length & 
 1)": for the compiler they are exactly the same, because
 the value is unsigned. And using a modulus is more clear here. 
 We are discussing about parity, not about bits.
That is a matter of opinion. If I see "% 2", my first thought is: we're checking for even... then I realize the "== 0" is missing.
I will add the == 0 too then.
 I wrote the task myself, so I should know.
Ah :-) I didn't know. OK. So it's the Python entry to be wrong and yours is correct.
 It's fine with me. I'm glad we got rid of the ugly cast.
I agree, that cast in D was a bug of mine. (I try to fix mistakes in your code, but once in a while my code introduces other bugs/problems. In such cases on GitHub you can annotate code, but on mediawiki you have to just "fix" the code. It wasn't designed for code.) Later I will change the code on Rosettacode. Bye, bearophile
Mar 24 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
 In the vampire code this doesn't happen because you return null 
 (that is represented by two zero words), but in general unlike 
 Python in D the safe and idiomatic way to test for array 
 emptiness is to use std.array.empty. Otherwise you risk having 
 problems.
I have just opened a thread in the main D newsgroup about this: http://forum.dlang.org/thread/bwgnbflygowctlisistg forum.dlang.org Bye, bearophile
Mar 24 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
This task has just a Tango entry:
http://rosettacode.org/wiki/Concurrent_computing


So I am writing a Phobos version. This seems to work as requested:


import std.stdio, std.random, std.parallelism, core.thread, 
core.time;

void main() {
     foreach (m; ["Enjoy", "Rosetta", "Code"])
         task!((s) {
             Thread.sleep(uniform(0, 1000).dur!"msecs");
             s.writeln;
         })(m).executeInNewThread;
}



I have also tried with a parallel foreach, the syntax is cleaner, 
but to me it always print the strings in the given order (so it's 
not doing what the task requires), do you know why?


import std.stdio, std.random, std.parallelism, core.thread, 
core.time;

void main() {
     foreach (s; ["Enjoy", "Rosetta", "Code"].parallel(1)) {
         Thread.sleep(uniform(0, 1000).dur!"msecs"); // Can't use 
UFCS.
         s.writeln;
     }
}


Bye,
bearophile
Mar 26 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 27-3-2013 0:20, bearophile wrote:
 This task has just a Tango entry:
 http://rosettacode.org/wiki/Concurrent_computing


 So I am writing a Phobos version. This seems to work as requested:


 import std.stdio, std.random, std.parallelism, core.thread, core.time;

 void main() {
      foreach (m; ["Enjoy", "Rosetta", "Code"])
          task!((s) {
              Thread.sleep(uniform(0, 1000).dur!"msecs");
              s.writeln;
          })(m).executeInNewThread;
 }



 I have also tried with a parallel foreach, the syntax is cleaner, but to me it
always print the strings in the given order (so it's not doing what the task
requires), do you know why?


 import std.stdio, std.random, std.parallelism, core.thread, core.time;

 void main() {
      foreach (s; ["Enjoy", "Rosetta", "Code"].parallel(1)) {
          Thread.sleep(uniform(0, 1000).dur!"msecs"); // Can't use UFCS.
          s.writeln;
      }
 }
Output on my system: C:\test Rosetta Enjoy Code C:\test Code Enjoy Rosetta C:\test Enjoy Rosetta Code C:\test Enjoy Code Rosetta C:\test Code Enjoy Rosetta
Mar 27 2013
next sibling parent Jos van Uden <usenet fwend.com> writes:
On 27-3-2013 15:17, Jos van Uden wrote:
 On 27-3-2013 0:20, bearophile wrote:
 This task has just a Tango entry:
 http://rosettacode.org/wiki/Concurrent_computing


 So I am writing a Phobos version. This seems to work as requested:


 import std.stdio, std.random, std.parallelism, core.thread, core.time;

 void main() {
      foreach (m; ["Enjoy", "Rosetta", "Code"])
          task!((s) {
              Thread.sleep(uniform(0, 1000).dur!"msecs");
              s.writeln;
          })(m).executeInNewThread;
 }



 I have also tried with a parallel foreach, the syntax is cleaner, but to me it
always print the strings in the given order (so it's not doing what the task
requires), do you know why?


 import std.stdio, std.random, std.parallelism, core.thread, core.time;

 void main() {
      foreach (s; ["Enjoy", "Rosetta", "Code"].parallel(1)) {
          Thread.sleep(uniform(0, 1000).dur!"msecs"); // Can't use UFCS.
          s.writeln;
      }
 }
(...) my system:
DMD32 D Compiler v2.062 win7 64 bits, i7 2600
Mar 27 2013
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 Output on my system:


 C:\test
 Rosetta
 Enjoy
 Code

 C:\test
 Code
 Enjoy
 Rosetta
Thank you for your test, I will replace the Rosettacode one with the nicer version. I don't know why the second doesn't work correctly on my system, while the first works. Bye, bearophile
Mar 27 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
I you want to take a look, I've seen that my translation of the 
Python entry was tagged as wrong:

http://rosettacode.org/wiki/Set_puzzle#Alternative_Version

Bye,
bearophile
Apr 05 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 5-4-2013 14:23, bearophile wrote:
 I you want to take a look, I've seen that my translation of the Python entry
was tagged as wrong:

 http://rosettacode.org/wiki/Set_puzzle#Alternative_Version
Ledrug tagged it. The output says: striped open open. That shouldn't happen.
Apr 05 2013
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 That shouldn't happen.
Do you know why that shouldn't happen? :-) Bye, bearophile
Apr 05 2013
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 http://rosettacode.org/wiki/Set_puzzle#Alternative_Version
Ledrug tagged it. The output says: striped open open. That shouldn't happen.
I don't know what's wrong, and why, so I've killed that alternative version... Bye, bearophile
Apr 06 2013
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Maybe there is a way to translate this Haskell version to D with 
bigints:

http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base#Haskell

Unrelated: now I have a kind of efficient longest common 
subsequence algorithm with O(n) memory usage. Maybe there is some 
interest for it in Phobos.

Bye,
bearophile
Apr 18 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Some of the last ones that are undone still:

http://rosettacode.org/wiki/Birthday_problem
http://rosettacode.org/wiki/Suffix_tree
http://rosettacode.org/wiki/Deming%27s_Funnel

Bye,
bearophile
Jun 13 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
There is also one D entry in need to be fixed (with Phobos):

http://rosettacode.org/wiki/Distributed_programming#D

Bye,
bearophile
Jun 14 2013
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Friday, 14 June 2013 at 22:17:16 UTC, bearophile wrote:
 http://rosettacode.org/wiki/Distributed_programming#D
It kinda sounds like the description calls for something like what web.d does: server: import arsd.web; class Foo : ApiProvider { export string hello(string name) { return "hello, " ~ name; } export int add(int a, int b) { return a + b; } } mixin FancyMain!Foo; client: import arsd.curl; import std.stdio; void main() { writeln(curl("http://example.com/server/hello?name=me")); } or javascript client: Foo.hello("me").get(alert); // will pop up "hello, me" or php client: $api = new Foo("http://example.com/server/"); echo $api->add(10, 20)->getSync(); // prints 30 (the code for this is generated automatically by web.d. I also wrote a bash [!] script to call arbitrary web.d functions remotely but have not actually done the same for D itself yet! The reason is for all my use cases, I can just call the D function without going through the http middle man because all the D is part of the same executable program. Interestingly, the D one would probably use a code generator like javascript rather than opDispatch like the bash and php examples do because the code generator could give more type safety.) This is a generic protocol, can handle many things at once, and uses pretty natural data structures. (The returned values can be almost anything, but the arguments must be all types that can be converted from strings or arrays of strings.) This actual example here uses several thousand lines of library code but if you think it would fit the description, I'm sure I can do a basic demo in far fewer lines using nothing but phobos.
Jun 14 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Adam D. Ruppe:

 This actual example here uses several thousand lines of library 
 code but if you think it would fit the description, I'm sure I 
 can do a basic demo in far fewer lines using nothing but phobos.
I think Rosettacode accepts code that uses libraries that are free. Take a look at the many Python entries for this task. So if you think this task can be implemented quickly using web.d, then use it :-) In some tasks I have appreciated solving the problems from the ground up, but in this task I think it's better to be lazy. Bye, bearophile
Jun 14 2013
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Friday, 14 June 2013 at 22:44:40 UTC, bearophile wrote:
 So if you think this task can be implemented quickly using
 web.d, then use it :-)
I just think it is really cool that D can do that kind of thing, so a brief implementation might be good to show people how it is done. I'll see about slapping something together over the weekend and posting it here.
Jun 14 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Adam D. Ruppe:

 I'll see about slapping something together over the weekend and 
 posting it here.
If you use a library, please also give the link to the library, so I can create a nearly empty page on Rosettacode about it. It's kind of needed. Bye, bearophile
Jun 14 2013
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
I made a network server/client that needs no library except 
Phobos. Came in a little under 500 lines but is quite generic:

http://arsdnet.net/dcode/server.d

The top of the file shows the usage program, then comes the code 
that could go in a library.

Basically you define an interface with a bunch of functions. The 
server writes a class that implements that interface and then 
mixes in the helper code that does the network talking. The 
network protocol is very basic, it just serializes the arguments 
and return values with function and sequence numbers to know what 
to call. The serializer only handles basic types, arrays, and 
some structs, it isn't much code.

On the client side, that class is automatically generated. It 
doesn't completely implement the interface though, because the 
functions are all async callbacks instead of return values.

Run it without arguments to be the server. Any arguments will 
cause it to be a client and connect to local host to run the 
example.
Jun 16 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Adam D. Ruppe:

 I made a network server/client that needs no library except 
 Phobos. Came in a little under 500 lines but is quite generic:
Normal Rosettacode entries are under 40-100 lines. Many entries are about 10-20 lines long. There are are few entries (in C or Ada) that reach 500 lines, but I think they miss the point of Rosettacode, where code is meant to illustrate, it's not a place for heavy implementations. That's why I suggested to just call a library... What do you suggest to do? Bye, bearophile
Jun 16 2013
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Sunday, 16 June 2013 at 23:06:40 UTC, bearophile wrote:
 Normal Rosettacode entries are under 40-100 lines. Many entries 
 are about 10-20 lines long.
I think that biases it toward giant standard libraries. I've joked before that we could just say: import rosettacode; mixin Distributed!(); and win the code golf every time! :P But this asks for something pretty generic and the Go version for instance uses a rpc package that looks pretty similar to what I did here. The only reason their thing is short is because it is in the stdlib. (I betcha Go's stdlib implementation is longer than 500 lines too!)
 What do you suggest to do?
We could break the file into two parts, and link to one. Just as I feared though, the structs don't work because mixing in their name doesn't get the right import either. This is one disappointing limitation of string mixins that I've hit before too, when doing default arguments in web.d. It works for basic types but not for enums because while I can get the string representation, I can't get the actual type anymore. It would be great if we could describe a very specific type in a string mixin that the compiler knows, even if the imports aren't necessarily there. If I remove the struct example, it works with separate modules, so let's try that for now until I can think of a solution to the general problem here. code: http://arsdnet.net/dcode/rpc-example.d library: https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/rpc.d
Jun 16 2013
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Adam D. Ruppe:

 and win the code golf every time! :P
Some Rosettacode D entries are a bit compressed, but that site is not for code golfing. It's just preferred to not write long programs, for several reasonable reasons.
 code:
 http://arsdnet.net/dcode/rpc-example.d

 library:
 https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/rpc.d
I have reformatted your code a little for the D standard of Rosettacode (72 columns max, etc): http://codepad.org/lAxAJwoG With your code I have found a dmd compiler bug, are you able and willing to further reduce this? import std.conv: to; import std.traits: ParameterTypeTuple; mixin template NetworkServer(Interface) { void callByNumber(int functionNumber, int sequenceNumber, const(ubyte)[] buffer) { string callCode() { string code; foreach(memIdx, member; __traits(allMembers, Interface)) { code ~= "\t\tcase " ~ to!string(memIdx + 1) ~ ":\n"; alias mem = PassThrough!(__traits(getMember, Interface, member)); foreach(i, arg; ParameterTypeTuple!mem) { auto istr = to!string(i); code ~= "\t\t\t" ~ arg.stringof ~ " arg" ~ istr ~ ";\n"; code ~= "\t\t\tbuffer = deserializeInto(buffer, arg" ~ istr ~ ");\n"; } code ~= "\t\tbreak;\n"; } return code; } switch(functionNumber) { mixin(callCode()); } } } template PassThrough(alias a) { alias PassThrough = a; } void deserializeInto(T)(inout(ubyte)[] buffer, ref T s) { s.length = 1; } mixin template NetworkClient(Interface) { private static void createClass() {} mixin(createClass()); } interface ExampleNetworkFunctions { void sayHello(in string); } class ExampleServer : ExampleNetworkFunctions { override void sayHello(in string) {} mixin NetworkServer!ExampleNetworkFunctions; } void main() {} Bye, bearophile
Jun 17 2013
parent reply "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On 2013-06-18, 05:00, bearophile wrote:

 With your code I have found a dmd compiler bug, are you able and willing  
 to further reduce this?
Tried this with 2.063.2, and there are three errors in the code - deserializeInto should return its buffer, the switch on line 19 needs a default: case, and deserializeInto tries to modify its non-buffer argument (which in this case is a const string. None of these seem to be a compiler bug. -- Simen
Jun 18 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Simen Kjaeraas:

 Tried this with 2.063.2, and there are three errors in the code 
 - deserializeInto
 should return its buffer, the switch on line 19 needs a 
 default: case, and
 deserializeInto tries to modify its non-buffer argument (which 
 in this case is a
 const string. None of these seem to be a compiler bug.
I have introduced the first two errors in the reduction process. The third is the one that triggers a crash of my DMD version. I am keeping my compiler updated, I have compiled it yesterday, and it crashes after giving the error: test.d(28): Error: cannot modify const expression s Now I don't know if it's a problem of just my compiler, or if it's a normal compiler bug. Bye, bearophile
Jun 18 2013
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Tuesday, 18 June 2013 at 09:22:05 UTC, bearophile wrote:
 third is the one that triggers a crash of my DMD version. I am 
 keeping my compiler updated, I have compiled it yesterday, and 
 it crashes after giving the error:

 test.d(28): Error: cannot modify const expression s

 Now I don't know if it's a problem of just my compiler, or if 
 it's a normal compiler bug.
Hmm, on my compiler it just fails to compile test11.d(32): Error: cannot modify const expression s test11.d(26): Error: template instance test11.deserializeInto!(const(immutable(char)[])) error instantiating which is actually expected because it is referring to this function: override void sayHello(in string) {} and the ParameterTypeTuple there will return a fully const type because of the "in", so assigning to it won't work without a cast. I can't reproduce the compiler crash you saw though.
Jun 18 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Adam D. Ruppe:

 I can't reproduce the compiler crash you saw though.
Thank you. Then it's somehow just my compiler... Bye, bearophile
Jun 18 2013
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Adam D. Ruppe:

 code:
 http://arsdnet.net/dcode/rpc-example.d

 library:
 https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/rpc.d
It's online: http://rosettacode.org/wiki/Distributed_programming#D Bye, bearophile
Jun 23 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
This entry has stopped working since lot of time:
http://rosettacode.org/wiki/MD5/Implementation#D

This is an improved version, but help is welcome:
http://codepad.org/g4RBio8E

Bye,
bearophile
Jul 16 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 http://codepad.org/g4RBio8E
this line: .replace("TT", "0x" ~ text(T(n), 16)); Needs to be: .replace("TT", "0x" ~ to!string(T(n), 16)); But the code in that link is all wrong because it needs all the code from std.md5 to work. And even then I don't know where Decode() is. Bye, bearophile
Jul 16 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
 But the code in that link is all wrong because it needs all the 
 code from std.md5 to work.
 And even then I don't know where Decode() is.
OK, the code now works :-) Bye, bearophile
Jul 16 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
 OK, the code now works :-)
And the results are a bit hilarious: ...>md5_implementation5_dmd md5 digest("") = D41D8CD98F00B204E9800998ECF8427E zmd5 digest("") = D41D8CD98F00B204E9800998ECF8427E Test performance / message size 200MBytes digest(data) = F083432AB71F6177A8EC2CA5157F7B83 std.md5: 16.59 M/sec ( 12.05 secs) digest(data) = F083432AB71F6177A8EC2CA5157F7B83 zmd5 : 81.90 M/sec ( 2.44 secs) ...>md5_implementation5_ldc md5 digest("") = D41D8CD98F00B204E9800998ECF8427E zmd5 digest("") = D41D8CD98F00B204E9800998ECF8427E Test performance / message size 200MBytes digest(data) = F083432AB71F6177A8EC2CA5157F7B83 std.md5: 112.36 M/sec ( 1.78 secs) digest(data) = F083432AB71F6177A8EC2CA5157F7B83 zmd5 : 98.18 M/sec ( 2.04 secs) The zmd5 version is generated asm with a small part in D. LDC2 compiles the standard D version even better... :-) Bye, bearophile
Jul 16 2013
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Now this D entry works again:
http://rosettacode.org/wiki/S-Expressions#D

Probably it can be written without explicit indexes, only using 
txt.front, txt.popFrontN, txt.find, etc. Do you want to produce 
such modified version?


This simple task shows well why a parser combinators like Parsec 
is better:
http://rosettacode.org/wiki/S-Expressions#Haskell

Bye,
bearophile
Jul 21 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
This D entry uses Tango, but it should also show a version for 
Phobos:

http://rosettacode.org/wiki/Rosetta_Code/Count_examples#D

Bye,
bearophile
Jul 25 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
 This D entry uses Tango, but it should also show a version for 
 Phobos:

 http://rosettacode.org/wiki/Rosetta_Code/Count_examples#D
Two versions The Mathematica solution is short: TaskList = Flatten[ Import["http://rosettacode.org/wiki/Category:Programming_Tasks", "Data"][[1, 1]]]; "Data"][[1,2]], example(s)"]& ~Map~ StringReplace[TaskList, " " -> "_"] This Perl solution is compact: use v5.10; use Mojo::UserAgent; my $site = "http://rosettacode.org"; my $list_url = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"; my $ua = Mojo::UserAgent->new; $ua->get("$site$list_url")->res->dom->find('cm')->each(sub { (my $slug = $_->{title}) =~ tr/ /_/; my $count = $ua->get("$site/wiki/$slug")->res->dom->find("#toc .toclevel-1")->size; say "$_->{title}: $count examples"; }); be fast: #r "System.Xml.Linq.dll" let uri1 = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" let uri2 task = sprintf "http://www.rosettacode.org/w/index.php?title=%s&action=raw" task [|for xml in (System.Xml.Linq.XDocument.Load uri1).Root.Descendants() do for attrib in xml.Attributes() do if attrib.Name.LocalName = "title" then yield async { let uri = uri2 (attrib.Value.Replace(" ", "_") |> System.Web.HttpUtility.UrlEncode) use client = new System.Net.WebClient() let! html = client.AsyncDownloadString(System.Uri uri) let sols' = html.Split([|"{{header|"|], System.StringSplitOptions.None).Length - 1 lock stdout (fun () -> printfn "%s: %d examples" attrib.Value sols') return sols' }|] |> Async.Parallel |> Async.RunSynchronously |> fun xs -> printfn "Total: %d examples" (Seq.sum xs) Bye, bearophile
Jul 25 2013
prev sibling next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
I have added a D entry for the "Go Fish" game:

http://rosettacode.org/wiki/Go_Fish#D

I don't know the Go Fish game, so I am not sure this code is 
correct. Is some of you able and willing to test its play a bit?

(This D entry is very Python-style because it's a translation of 
the Python entry, so it's not very strongly typed. Generally in D 
I prefer stronger typing, but in this case I think it's 
acceptable).

Bye,
bearophile
Aug 30 2013
next sibling parent reply maarten van damme <maartenvd1994 gmail.com> writes:
the entry :
http://rosettacode.org/wiki/File_IO
is wrong because as stated by the asignment : "In this task, the job is to
create a file called "output.txt", and place in it the contents of the file
"input.txt", *via an intermediate variable.**"*
*
*
there is no intermediate variable; I don't know if this is the right place
to post but you seem to do a lot of work for rosetta...


2013/8/31 bearophile <bearophileHUGS lycos.com>

 I have added a D entry for the "Go Fish" game:

 http://rosettacode.org/wiki/**Go_Fish#D<http://rosettacode.org/wiki/Go_Fish#D>

 I don't know the Go Fish game, so I am not sure this code is correct. Is
 some of you able and willing to test its play a bit?

 (This D entry is very Python-style because it's a translation of the
 Python entry, so it's not very strongly typed. Generally in D I prefer
 stronger typing, but in this case I think it's acceptable).

 Bye,
 bearophile
Aug 30 2013
parent reply Jos van Uden <usenet fwend.com> writes:
On 31-8-2013 4:08, maarten van damme wrote:
 the entry :
 http://rosettacode.org/wiki/File_IO
 is wrong because as stated by the asignment : "In this task, the job is to
create a file called "output.txt", and place in it the contents of the file
"input.txt", /via an intermediate variable.//"/
 /
 /
 there is no intermediate variable; I don't know if this is the right place to
post but you seem to do a lot of work for rosetta...
It's an old task (from 2007). The task description was changed after the D entries were made. http://rosettacode.org/mw/index.php?title=File_IO&diff=25166&oldid=21823 So it needs to be updated. Perhaps you will do the honors? :)
Aug 30 2013
parent "bearophile" <bearophileHUGS lycos.com> writes:
Jos van Uden:

 It's an old task (from 2007). The task description was changed 
 after the D entries were made.
Yes, there are about 63 Rosettacode tasks that I have not yet updated: accumulator_factory.d address_of_a_variable.d animation.d boolean_values.d call_a_function_in_a_shared_library.d collections.d concurrent_computing.d create_an_object_at_a_given_address.d create_a_file.d date_format.d delete_a_file.d distributed_programming.d echo_server.d environment_variables.d execute_a_system_command.d execute_snusp.d file_io.d first_class_functions_use_numbers_analogously.d flow_control_structures.d formal_power_series.d fractal_tree2.d globally_replace_text_in_several_files.d hello_world_graphical.d http.d image_noise.d include_a_file.d input_loop.d json.d literals_floating_point.d literals_string.d memory_layout_of_a_data_structure.d metered_concurrency.d multiple_distinct_objects.d mutex.d object_serialization.d opengl.d parallel_calculations1.d pointers_and_references.d pragmatic_directives.d quine.d rc_24_game.d rename_a_file.d rosetta_code_count_examples.d scripted_main.d secure_temporary_file.d shell_one_liner.d simple_windowed_application.d singleton.d sockets.d synchronous_concurrency.d system_time.d test_a_function.d user_input_text.d variables.d variable_size_get.d variable_size_set.d walk_a_directory_non_recursively.d walk_a_directory_recursively.d window_creation.d xml_dom_serialization.d xml_input.d xml_output.d xml_xpath.d Bye, bearophile
Aug 31 2013
prev sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
On Saturday, 31 August 2013 at 01:42:43 UTC, bearophile wrote:
 I have added a D entry for the "Go Fish" game:
hmm there's too much text output, it makes following the game hard, and seeing what the computer drew means you can cheat! But I think it plays correctly, I was able to finish a game. -- Speaking of card games, did you know Windows comes with a cards.dll that can draw a set of playing cards? It is used for built in games like Solitare. And you can use it too! Here's an example of how: http://arsdnet.net/dcode/wincards.d See the main function at the bottom of the file. The main() depends on (the newer version of) my simpledisplay.d and color.d (also shows how to use some of the input event improvements I've made over the last couple weeks!) https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff The sample program puts two cards on the screen and lets you drag them around with the mouse. Only works on MS Windows.
Aug 30 2013
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
This D1 entry needs an update:
http://rosettacode.org/wiki/Metered_concurrency#D

Is someone willing to update it?


import std.stdio, core.thread, std.c.time;

class Semaphore {
     private int lockCnt, maxCnt;

     this(in int count) {
         maxCnt = lockCnt = count;
     }

     void acquire() {
         if (lockCnt < 0 || maxCnt <= 0)
             throw new Exception("Negative Lock or Zero init. 
Lock");
         while(lockCnt == 0)
             Thread.getThis.yield; // Let other threads release 
lock.
         synchronized lockCnt--;
     }

     void release() {
         synchronized
             if (lockCnt < maxCnt)
                 lockCnt++;
             else
                 throw new Exception("Release lock before 
acquire");
     }

     int getCnt() {
         synchronized return lockCnt;
     }
}

class Worker : Thread {
     private static int id = 0;
     private Semaphore lock;
     private int myId;

     this (Semaphore l) {
         super();
         lock = l;
         myId = id++;
     }

     int run() {
         lock.acquire;
         writefln("Worker %d got a lock(%d left).", myId, 
lock.getCnt);
         msleep(2_000); // Wait 2.0 seconds.
         lock.release;
         writefln("Worker %d released a lock(%d left).",
                  myId, lock.getCnt);
         return 0;
     }
}

void main() {
     Worker[10] crew;
     Semaphore lock = new Semaphore(4);

     foreach (ref c; crew)
         (c = new Worker(lock)).start;
     foreach (ref c; crew)
         c.wait;
}


Bye,
bearophile
Nov 25 2013
prev sibling next sibling parent reply "qznc" <qznc web.de> writes:
I just made some scripts [0] to download and compile all D 
examples from Rosettacode. From 186 of 716 examples fail to 
compile [1]. Some for trivial reasons like not wrapped into a 
main function or a missing import. Some require SDL or Tango or 
other third-party libraries.

My ultimate goal was to use this for regression testing dmd. 
Anyways if people try code examples they should compile out of 
the box for good PR.

If you are looking for a low-barrier way to support D a little, 
feel free to check out the fail list [1] and fix some. :)

[0] 
https://bitbucket.org/qznc/rosetta/src/da12e3673b0d/compile_all/?at=master
[1] https://gist.github.com/qznc/9ba4b0e78abfc35d4694
Jan 15 2014
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
qznc:

 I just made some scripts [0] to download and compile all D 
 examples from Rosettacode. From 186 of 716 examples fail to 
 compile [1]. Some for trivial reasons like not wrapped into a 
 main function or a missing import. Some require SDL or Tango or 
 other third-party libraries.

 My ultimate goal was to use this for regression testing dmd. 
 Anyways if people try code examples they should compile out of 
 the box for good PR.

 If you are looking for a low-barrier way to support D a little, 
 feel free to check out the fail list [1] and fix some. :)

 [0] 
 https://bitbucket.org/qznc/rosetta/src/da12e3673b0d/compile_all/?at=master
 [1] https://gist.github.com/qznc/9ba4b0e78abfc35d4694
I am using similar scripts written in Python since years. Currently there are around 760-770 D programs in Rosettacode. What version of the D compiler are you using? I am assuming Rosettacode to be compilable with the latest "bleeding edge" compiler. So if you use the latest released compiler some of the entries will not compile. Such entries should not be "fixed" at all. Your list of failing to compile just say "fail", but there are several reasons for a program to fail. Some programs need a "modulename_main" version to be compiled, because D lacks a built-in way to tell apart the main module of a program from the other modules. (In Python you use the "if __name__ == '__main__':" for this purpose). Some programs don't compile because require Tango. I have not removed them all because some Tango programmer has written them and I guess such person doesn't like to see their work removed from the pages. Some entries don't compile because they are not yet updated, or dmd has had some regressions. Thankfully Kenji usually fixes such regressions in just few days when I find them. Bye, bearophile
Jan 15 2014
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
 https://bitbucket.org/qznc/rosetta/src/da12e3673b0d/compile_all/?at=master
 [1] https://gist.github.com/qznc/9ba4b0e78abfc35d4694
Regarding Task names that start with a number, like rosettacode_24_game_solve_00.d, I usually prefix them with "rc_". Bye, bearophile
Jan 15 2014
prev sibling next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
 [0] 
 https://bitbucket.org/qznc/rosetta/src/da12e3673b0d/compile_all/?at=master
 [1] https://gist.github.com/qznc/9ba4b0e78abfc35d4694
Another reason for some of your entries to not compile seems to be that you have missed that some entries need other entries to compile, so "rc_24_game_solve.d" needs "permutations2.d" and "arithmetic_rational.d", and then compiles and runs fine. (I number 1 2 3 ... the tasks that have more than one D solution). Bye, bearophile
Jan 15 2014
prev sibling parent reply Brad Roberts <braddr puremagic.com> writes:
On 1/15/14 4:18 PM, bearophile wrote:

 What version of the D compiler are you using? I am assuming Rosettacode to be
compilable with the
 latest "bleeding edge" compiler. So if you use the latest released compiler
some of the entries will
 not compile. Such entries should not be "fixed" at all.
I think this is a mistake. They should compile with a released compiler. They also likely form a potentially interesting set of regression tests that someone ought to volunteer to test beta's against.
Jan 15 2014
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Brad Roberts:

 I think this is a mistake.  They should compile with a released 
 compiler.
Why? And why do you think that outweighs the several advantages of having entries compilable only with the latest beta compiler? (Currently there are 40-50 entries that don't compile with the released dmd 2.064.)
 They also likely form a potentially interesting set of 
 regression tests that someone ought to volunteer to test beta's 
 against.
Rosettacode site has many different purposes; I also use those programs to test the dmd compiler for regressions. But to do this effectively you have to use the latest compiler changes. Also, how can you update manually on the site tens of entries all at once when a new compiler comes out? Bye, bearophile
Jan 15 2014
parent reply Brad Roberts <braddr puremagic.com> writes:
On 1/15/14 4:42 PM, bearophile wrote:
 Brad Roberts:

 I think this is a mistake.  They should compile with a released compiler.
Why? And why do you think that outweighs the several advantages of having entries compilable only with the latest beta compiler? (Currently there are 40-50 entries that don't compile with the released dmd 2.064.)
Requiring that users of the code in resottacode be using bleeding edge, unreleased, compilers is a disservice to those users. Typical users will not and should not need to use anything other than a released compiler.
 They also likely form a potentially interesting set of regression tests that
someone ought to
 volunteer to test beta's against.
Rosettacode site has many different purposes; I also use those programs to test the dmd compiler for regressions. But to do this effectively you have to use the latest compiler changes. Also, how can you update manually on the site tens of entries all at once when a new compiler comes out?
The point is you shouldn't have to, unless the code is taking advantage of broken behavior. Any changes that 'have' to be made due to a compiler release need to be carefully examined as probable regressions in the compiler.
Jan 15 2014
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Brad Roberts:

 Requiring that users of the code in resottacode be using 
 bleeding edge, unreleased, compilers is a disservice to those 
 users.  Typical users will not and should not need to use 
 anything other than a released compiler.
Some of the rosettacode usages/purposes are: - Trying new compiler features to see if they work correctly; - Try the new compiler features to learn to use them effectively; - To test the compiler betas to see if they have "regressions" if you try to use the new features. - To show "good" (== short, fast, elegant, clean) D code, thanks to some nicer recently introduced compiler improvements; So do you want to throw away those purposes? Also keep in mind that if you throw away those purposes, I will lose some of my desire to work on Rosettacode, so you will have a less good and less updated rosettacode site. And I have found probably more than 300 dmd bugs/regressions thanks to those beta-related purposes. If you throw away those purposes you will lose a significant amount of my future bug reports. Are those prices low enough for you?
 The point is you shouldn't have to, unless the code is taking 
 advantage of broken behavior.  Any changes that 'have' to be 
 made due to a compiler release need to be carefully examined as 
 probable regressions in the compiler.
One of the points of improving a compiler is offering new features that are advantageous to use. If you don't want to use them it often means they are a failure. In many other cases the dmd compiler rejects older code that was wrong, because it becomes more tight. Rosettacode tasks are usually short. If you don't try new compiler features in such little programs that have no production-level significance, then you will never try them in production code, and you will probably use just C-like code. Being a little compiler-bold in those tasks is acceptable. Bye, bearophile
Jan 15 2014
parent reply "qznc" <qznc web.de> writes:
On Thursday, 16 January 2014 at 01:11:23 UTC, bearophile wrote:
 - To test the compiler betas to see if they have "regressions" 
 if you try to use the new features.
This sounds somewhat paradox to me. How can a new feature have a regression? A "regression" means it has worked before, but new feature did not exist before. Maybe the question is about "before"? In my understanding "before" is "latest release", whereas "current" is "beta release" or "git HEAD". Do you mean "before" as something like "commit deadbeef~4" whereas "current" is "commit deadbeef"? I see nothing wrong with using code from Rosettacode to try out new features. It is weird though, if people want to test an example, you have to tell them to compile dmd from git. In practice the difference between the uses is not that important I think, because the sheer number of code snippets and release frequency means that most examples can be compiled with the latest release no matter what bearophile does. ;) Btw are your scripts public, bearophile?
Jan 15 2014
parent "bearophile" <bearophileHUGS lycos.com> writes:
qznc:

 This sounds somewhat paradox to me. How can a new feature have 
 a regression? A "regression" means it has worked before, but 
 new feature did not exist before.
"Regressions" on older betas; or to see if using the new features breaks other apparently unrelated parts of old code.
 In practice the difference between the uses is not that 
 important I think, because the sheer number of code snippets 
 and release frequency means that most examples can be compiled 
 with the latest release no matter what bearophile does. ;)
Right. The percentage of future compilable entries is small, usually much less than 5%. And this was even more true in past, when the frequency of D releases was higher.
 Btw are your scripts public, bearophile?
They are the common kind of little scripts that you prefer to rewrite on your own. Bye, bearophile
Jan 16 2014
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
qznc:

 [0] 
 https://bitbucket.org/qznc/rosetta/src/da12e3673b0d/compile_all/?at=master
 [1] https://gist.github.com/qznc/9ba4b0e78abfc35d4694
Few of the tasks of your list were never updated to D2/Phobos, and they should be updated. Among the ones that are updated, I have found five that don't compile on dmd 2.065 because of compiler changes and one (I think already reported) regression in std.array.array: arithmetic_evaluation.d balanced_ternary.d combinations_with_repetitions1.d k_means_plus_plus_clustering.d names_to_numbers.d or number_names.d I will try to fix them (and probably I will leave the one with a regression untouched). Bye, bearophile
Jan 15 2014
parent "bearophile" <bearophileHUGS lycos.com> writes:
 arithmetic_evaluation.d
 balanced_ternary.d
 combinations_with_repetitions1.d
 k_means_plus_plus_clustering.d
 names_to_numbers.d or number_names.d
I have "fixed" them. This is the problem in array, already in Bugzilla, I think it's a kind of regression: import std.array: array; immutable foo = [""].array; void main() {} The problem with inout in balanced_ternary.d was caused by inout semantics that keeps subtly changing every month. I don't know the causes of such micro-regressions. Bye, bearophile
Jan 15 2014
prev sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Is someone willing to write a D entry for this?

http://rosettacode.org/wiki/Rendezvous

Bye,
bearophile
Feb 25 2014
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 02/25/2014 03:48 PM, bearophile wrote:
 Is someone willing to write a D entry for this?

 http://rosettacode.org/wiki/Rendezvous

 Bye,
 bearophile
I think the following satisfies the requirements. Improve at will! :p import std.stdio; import std.exception; import std.array; import std.concurrency; import std.datetime; import core.thread; class OutOfInk : Exception { this() { super("Out of ink."); } } struct Printer { string id; size_t ink; void print(string line) { enforce(ink != 0, new OutOfInk); writefln("%s: %s", id, line); --ink; } } struct PrinterRendezvous { Printer[] printers; void print(string[] lines) shared { Exception savedException; while (true) { if (lines.empty) { break; } if (printers.empty) { // No more printers to try assert(savedException !is null); throw savedException; } try { synchronized { (cast(Printer)printers.front).print(lines.front); } lines.popFront(); // Increase the chance of interleaved output Thread.sleep(10.msecs); } catch (OutOfInk exc) { savedException = exc; synchronized { // Switch to the next printer printers = printers[1..$]; } } } } } void humptyDumptyTask(ref shared(PrinterRendezvous) rendezvous) { auto humptyDumpty = [ "Humpty Dumpty sat on a wall.", "Humpty Dumpty had a great fall.", "All the king's horses and all the king's men,", "Couldn't put Humpty together again.", ]; rendezvous.print(humptyDumpty); } void motherGooseTask(ref shared(PrinterRendezvous) rendezvous) { auto motherGoose = [ "Old Mother Goose,", "When she wanted to wander,", "Would ride through the air,", "On a very fine gander.", "Jack's mother came in,", "And caught the goose soon,", "And mounting its back,", "Flew up to the moon.", ]; rendezvous.print(motherGoose); } void main() { auto rendezvous = shared(PrinterRendezvous)([ Printer("main", 5), Printer("reserve", 5) ]); spawn(&humptyDumptyTask, rendezvous); spawn(&motherGooseTask, rendezvous); } Sample output: main: Humpty Dumpty sat on a wall. main: Old Mother Goose, main: Humpty Dumpty had a great fall. main: When she wanted to wander, main: All the king's horses and all the king's men, reserve: Would ride through the air, reserve: Couldn't put Humpty together again. reserve: On a very fine gander. reserve: Jack's mother came in, reserve: And caught the goose soon, deneme.OutOfInk deneme.d([...]): Out of ink. Ali
Feb 25 2014
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Ali Çehreli:

Improve at will! :p
I will mostly just uniform its formatting to all the other Rosettacode entries, shorten the lines to 72 chars, etc.
                 synchronized {
                     // Switch to the next printer
                     printers = printers[1..$];
                 }
This doesn't work: printers.popFront();
     void print(string line)
     {
         enforce(ink != 0, new OutOfInk);
         writefln("%s: %s", id, line);
         --ink;
     }
 }

 struct PrinterRendezvous
 ...
             try {
                 synchronized {
                     
 (cast(Printer)printers.front).print(lines.front);
                 }
It it a good idea to define Printer.print like this to remove that cast? void print(string line) shared Bye, bearophile
Feb 26 2014
next sibling parent reply "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
On Wednesday, 26 February 2014 at 11:24:58 UTC, bearophile wrote:
 Ali Çehreli:
                synchronized {
                    // Switch to the next printer
                    printers = printers[1..$];
                }
This doesn't work: printers.popFront();
Yes, because typeof(printers) == shared. I'm wondering why front() works.
            try {
                synchronized {
                    
 (cast(Printer)printers.front).print(lines.front);
                }
It it a good idea to define Printer.print like this to remove that cast? void print(string line) shared
No it is not, because the implementation of print() would be invalid then: void print(string line) shared { enforce(ink != 0, new OutOfInk); // ink != 0 is not valid code writefln("%s: %s", id, line); --ink; // --ink is not valid code } By declaring the method "shared" you promise that any acess to shared data in this method is safe. Using naked operators on shared scalar variables will eventually be disallowed, you'll have to explicitly use atomic operations. You'd also have to synchronize access to id member, because it is public. Although "immutable" means "implicitly shared", id being public means that potentionally one thread could be performing assigment to it while another one reads from it. Slices are two machine words, so atomicity of reads/writes is not implicitly guaranteed. The cast in this case is safe and better approach because all access to "printers" is synchronized. If/when https://d.puremagic.com/issues/show_bug.cgi?id=12133 and the corresponding pull is accepted, the cast could be replaced with printers.assumeLocal.front.print(lines.front); which states the intent even more clearly, IMO.
Feb 26 2014
parent reply "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
I forgot to note that both synchronized {} blocks should also be 
synchronizing on the same mutex. Right now it's two different 
critical sections, so a race is still possible, i.e. while one 
thread is printing the other may be removing the first printer. 
Run the code several times and you'll no doubt stumble upon it.

The mutex could be emulated with a shared bool and 
std.atomic.cas(). That would get rid of synchronized{} blocks and 
would potentionally be faster.
Feb 26 2014
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Stanislav Blinov:

 You'd also have to synchronize access to id member,
 I forgot to note that both synchronized {} blocks should also 
 be synchronizing on the same mutex.
 The mutex could be emulated with a shared bool and 
 std.atomic.cas(). That would get rid of synchronized{} blocks 
 and would potentionally be faster.
This is the current D entry: http://rosettacode.org/wiki/Rendezvous#D If you have bug fixes, or improvements, it's better to do them right there. Of if you don't want to register on that site, you can put the modified version in dpaste, and I'll upload it on Rosettacode. Bye, bearophile
Feb 26 2014
parent "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
On Wednesday, 26 February 2014 at 12:58:26 UTC, bearophile wrote:

 If you have bug fixes, or improvements, it's better to do them 
 right there. Of if you don't want to register on that site, you 
 can put the modified version in dpaste, and I'll upload it on 
 Rosettacode.
Here are some improvements: http://dpaste.dzfl.pl/6430488f3d07 The changes are minimal just to accomodate for simple synchronization primitive. Full-blown Mutex version would be a little more involved, and somewhat ugly, at least until the upcoming migration of Mutex et al. to 'shared' takes place.
Feb 26 2014
prev sibling parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 02/26/2014 04:46 AM, Stanislav Blinov wrote:

 I forgot to note that both synchronized {} blocks should also be
 synchronizing on the same mutex.
Oh, that's a good one! :)
 Run the code several times and you'll no doubt stumble upon it.
But I had inserted that Sleep() in there. Isn't that the solution for all multi-threading problems? :p Ali
Feb 26 2014
prev sibling parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 02/26/2014 03:24 AM, bearophile wrote:

 Ali Çehreli:

 Improve at will! :p
I will mostly just uniform its formatting to all the other Rosettacode entries, shorten the lines to 72 chars, etc.
                 synchronized {
                     // Switch to the next printer
                     printers = printers[1..$];
                 }
This doesn't work: printers.popFront();
I've noticed that too. ;) And I am not sure why the slicing syntax works because the 'printers' member is still shared then.
     void print(string line)
     {
         enforce(ink != 0, new OutOfInk);
         writefln("%s: %s", id, line);
         --ink;
     }
 }

 struct PrinterRendezvous
 ...
             try {
                 synchronized {
 (cast(Printer)printers.front).print(lines.front);
                 }
It it a good idea to define Printer.print like this to remove that cast? void print(string line) shared
I had that at one point but then I could not convince myself that Printer.print should be a shared member function. How do we know at design time that every Printer would be shared? I thought that Printer should be as simple as possible and that shared should be handled by a higher-level code. Then the code became ugly like that. :) I need more experience. :-/
 Bye,
 bearophile
Ali
Feb 26 2014
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Ali Çehreli:

 And I am not sure why the slicing syntax works because the 
 'printers' member is still shared then.
Probably it's a known D implementation fault meant to be eventually fixed. ------------- Stanislav Blinov:
 Here are some improvements:
 http://dpaste.dzfl.pl/6430488f3d07
Updated the site with your code (in that the "View history" shows both your names): http://rosettacode.org/wiki/Rendezvous#D Bye, bearophile
Feb 26 2014
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 02/26/2014 06:58 AM, bearophile wrote:

 Updated the site
 http://rosettacode.org/wiki/Rendezvous#D
Thanks for posting the problem to begin with. I've learned a lot. Ali
Feb 26 2014
prev sibling parent reply "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
On Wednesday, 26 February 2014 at 14:54:05 UTC, Ali Çehreli wrote:
 On 02/26/2014 03:24 AM, bearophile wrote:

 Ali Çehreli:

 Improve at will! :p
I will mostly just uniform its formatting to all the other
Rosettacode
 entries, shorten the lines to 72 chars, etc.


                 synchronized {
                     // Switch to the next printer
                     printers = printers[1..$];
                 }
This doesn't work: printers.popFront();
I've noticed that too. ;) And I am not sure why the slicing syntax works because the 'printers' member is still shared then.
It fails to deduce argument types due to popFront() taking its argument by ref. That's actually good it caught that, because I don't think that slicing should be allowed either.
 It it a good idea to define Printer.print like this to remove
that cast?
 void print(string line) shared
I had that at one point but then I could not convince myself that Printer.print should be a shared member function. How do we know at design time that every Printer would be shared? I thought that Printer should be as simple as possible and that shared should be handled by a higher-level code. Then the code became ugly like that. :)
Indeed it shouldn't really be shared in this case, since it's used exclusively in the terms of lock-based synchronization. Ideally, it could be made entirely private to RendezvoudPrinter. But the transitivity of "shared" keyword still forces us to apply casts. It has little to do with experience. The whole 'shared' concept being incomplete in the language is a shame. Hopefully things will get better in the near future. As for slicing syntax for shared arrays, personally I think it should be disallowed, just like operators for shared scalars. But that would mean that calling front() would be illegal too, thus forcing the cast on the whole array when it's safe to do so... Oh, there is still much to discuss on this matter.
Feb 26 2014
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Stanislav Blinov:

 The whole 'shared' concept being incomplete in the language is 
 a shame. Hopefully things will get better in the near future.

 As for slicing syntax for shared arrays, personally I think it 
 should be disallowed, just like operators for shared scalars. 
 But that would mean that calling front() would be illegal too, 
 thus forcing the cast on the whole array when it's safe to do 
 so... Oh, there is still much to discuss on this matter.
I am not seeing much discussion on such topics in the near future. It's one of the most significant bugs of D (bigger than the unimplemented "scope"). This is why Andrei lately is not fond of large discussions about little enhancement requests in the main D newsgroup: there are plenty of significant parts still unfinished. Bye, bearophile
Feb 26 2014
parent "Stanislav Blinov" <stanislav.blinov gmail.com> writes:
Thank you for posting the code. However, I think there might be a 
subtle bug with my synchronization on bools, but I need to 
comtemplate on it some more to be sure :)

On Wednesday, 26 February 2014 at 15:52:24 UTC, bearophile wrote:
 Stanislav Blinov:
 Oh, there is still much to discuss on this matter.
I am not seeing much discussion on such topics in the near future. It's one of the most significant bugs of D (bigger than the unimplemented "scope"). This is why Andrei lately is not fond of large discussions about little enhancement requests in the main D newsgroup: there are plenty of significant parts still unfinished.
He has recently stated that this should be a focus this year: http://forum.dlang.org/post/ldnv5g$1osi$1 digitalmars.com. I'm hoping to get some time this weekend to get to that wiki page business...
Feb 26 2014