Re: A little of coordination for Rosettacode

2014-08-14 Thread bearophile via Digitalmars-d-learn

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


Re: A little of coordination for Rosettacode

2014-08-07 Thread safety0ff via Digitalmars-d-learn

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


Re: A little of coordination for Rosettacode

2014-07-31 Thread safety0ff via Digitalmars-d-learn

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.


Re: A little of coordination for Rosettacode

2014-07-31 Thread bearophile via Digitalmars-d-learn

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


Re: A little of coordination for Rosettacode

2014-02-26 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-02-26 Thread Stanislav Blinov

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.


Re: A little of coordination for Rosettacode

2014-02-26 Thread Stanislav Blinov
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.


Re: A little of coordination for Rosettacode

2014-02-26 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-02-26 Thread Stanislav Blinov

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.


Re: A little of coordination for Rosettacode

2014-02-26 Thread Ali Çehreli

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



Re: A little of coordination for Rosettacode

2014-02-26 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-02-26 Thread Ali Çehreli

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



Re: A little of coordination for Rosettacode

2014-02-26 Thread Ali Çehreli

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



Re: A little of coordination for Rosettacode

2014-02-26 Thread Stanislav Blinov

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.


Re: A little of coordination for Rosettacode

2014-02-26 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-02-26 Thread Stanislav Blinov
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...


Re: A little of coordination for Rosettacode

2014-02-25 Thread bearophile

Is someone willing to write a D entry for this?

http://rosettacode.org/wiki/Rendezvous

Bye,
bearophile


Re: A little of coordination for Rosettacode

2014-02-25 Thread Ali Çehreli

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



Re: A little of coordination for Rosettacode

2014-01-16 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-01-15 Thread 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


Re: A little of coordination for Rosettacode

2014-01-15 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-01-15 Thread Brad Roberts

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.





Re: A little of coordination for Rosettacode

2014-01-15 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-01-15 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-01-15 Thread bearophile

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


Re: A little of coordination for Rosettacode

2014-01-15 Thread qznc

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?


Re: A little of coordination for Rosettacode

2013-11-25 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-08-31 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-08-30 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-08-30 Thread maarten van damme
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 bearophileh...@lycos.com

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

 http://rosettacode.org/wiki/**Go_Fish#Dhttp://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



Re: A little of coordination for Rosettacode

2013-08-30 Thread Adam D. Ruppe

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.


Re: A little of coordination for Rosettacode

2013-08-30 Thread Jos van Uden

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_IOdiff=25166oldid=21823

So it needs to be updated. Perhaps you will do the honors? :)





Re: A little of coordination for Rosettacode

2013-07-25 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-07-25 Thread bearophile
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]]];

Print[Task \, StringReplace[#, _ -  ], \ has ,
  Length@Select[Import[http://rosettacode.org/wiki/;  #, 
Data][[1,2]],
  StringFreeQ[#, __ ~~ Programming Task | __ ~~ Omit] ],  
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=querylist=categorymemberscmtitle=Category:Programming_Taskscmlimit=500format=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;
});



The F# solution performs downloads concurrently and it's said to 
be fast:


#r System.Xml.Linq.dll

let uri1 = 
http://www.rosettacode.org/w/api.php?action=querylist=categorymemberscmtitle=Category:Programming_Taskscmlimit=500format=xml;
let uri2 task = sprintf 
http://www.rosettacode.org/w/index.php?title=%saction=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


Re: A little of coordination for Rosettacode

2013-07-21 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-07-16 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-07-16 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-07-16 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-07-16 Thread bearophile

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


Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-07-03 Thread Marco Leise
Am Sat, 22 Jun 2013 23:27:00 +0200
schrieb bearophile bearophileh...@lycos.com:

 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...

That would be me. Let's see where it goes.
 
 Bye,
 bearophile

-- 
Marco



Re: A little of coordination for Rosettacode

2013-06-23 Thread bearophile

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


Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-06-23 Thread Brian Rogoff

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


Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-06-22 Thread Brian Rogoff

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,

 2core.sync.mutex;
 3  
 4  void eat(in uint i, in string name, Mutex[] forks) {
 5writeln(name,  is hungry.);
 6  
 7immutable j = (i + 1) % forks.length;
 8  
 9	  // Take forks i and j. The lower one first to prevent 
deadlock.

10auto fork1 = forks[min(i, j)];
11auto fork2 = forks[max(i, j)];
12  
13fork1.lock();
14scope(exit) fork1.unlock();
15  
16fork2.lock();
17scope(exit) fork2.unlock();
18  
19writeln(name,  is eating.);
20writeln(name,  is full.);
21  }
22  
23  void think(in string name) {
24writeln(name,  is thinking.);
25  }
26  
27  void main() {
28	  const philosophers = Aristotle Kant Spinoza Marx 
Russell.split();

29Mutex[philosophers.length] forks;
30foreach (ref fork; forks)
31  fork = new Mutex();
32  
33defaultPoolThreads = forks.length;
34	  foreach (uint i, philo; taskPool.parallel(philosophers)) 
{

35  foreach (_; 0 .. 100) {
36eat(i, philo, forks);
37think(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





Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-06-22 Thread bearophile

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


Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-06-22 Thread Ali Çehreli

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.


   4void 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



Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-06-22 Thread bearophile

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


Re: Ping qznc: Re: A little of coordination for Rosettacode

2013-06-22 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-06-18 Thread Simen Kjaeraas

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


Re: A little of coordination for Rosettacode

2013-06-18 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-06-18 Thread Adam D. Ruppe

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.


Re: A little of coordination for Rosettacode

2013-06-18 Thread bearophile

Adam D. Ruppe:


I can't reproduce the compiler crash you saw though.


Thank you. Then it's somehow just my compiler...

Bye,
bearophile


Re: A little of coordination for Rosettacode

2013-06-17 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-06-16 Thread 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:


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.


Re: A little of coordination for Rosettacode

2013-06-16 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-06-16 Thread Adam D. Ruppe

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


Re: A little of coordination for Rosettacode

2013-06-14 Thread bearophile

There is also one D entry in need to be fixed (with Phobos):

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

Bye,
bearophile


Re: A little of coordination for Rosettacode

2013-06-14 Thread Adam D. Ruppe

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.


Re: A little of coordination for Rosettacode

2013-06-14 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-06-14 Thread Adam D. Ruppe

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.


Re: A little of coordination for Rosettacode

2013-06-14 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-06-13 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-04-18 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-04-06 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-04-05 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-04-05 Thread Jos van Uden

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.


Re: A little of coordination for Rosettacode

2013-04-05 Thread bearophile

Jos van Uden:


That shouldn't happen.


Do you know why that shouldn't happen? :-)

Bye,
bearophile


Re: A little of coordination for Rosettacode

2013-03-27 Thread Jos van Uden

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





Re: A little of coordination for Rosettacode

2013-03-27 Thread Jos van Uden

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



Re: A little of coordination for Rosettacode

2013-03-27 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-26 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-24 Thread bearophile
Some comments about the recently created Vampire number task in 
Rosettacode:


The version I have modified:
http://rosettacode.org/mw/index.php?title=Vampire_numberdiff=154069oldid=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


Re: A little of coordination for Rosettacode

2013-03-24 Thread bearophile
- 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


Re: A little of coordination for Rosettacode

2013-03-24 Thread bearophile

A new version of Vampire number, do you like it?

http://codepad.org/DaVxWpoA

Bye,
bearophile


Re: A little of coordination for Rosettacode

2013-03-24 Thread Jos van Uden

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_numberdiff=154069oldid=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.



Re: A little of coordination for Rosettacode

2013-03-24 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-24 Thread bearophile
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/bwgnbflygowctlisi...@forum.dlang.org

Bye,
bearophile



Re: A little of coordination for Rosettacode

2013-03-20 Thread ixid

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.


Re: A little of coordination for Rosettacode

2013-03-20 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-19 Thread ixid
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.


Re: A little of coordination for Rosettacode

2013-03-19 Thread Andrea Fontana


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;
}


Re: A little of coordination for Rosettacode

2013-03-19 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-19 Thread ixid

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.


Re: A little of coordination for Rosettacode

2013-03-19 Thread ixid

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.


Re: A little of coordination for Rosettacode

2013-03-19 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-05 Thread Jos van Uden

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);
}



Re: A little of coordination for Rosettacode

2013-03-05 Thread Jos van Uden

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();
 



Re: A little of coordination for Rosettacode

2013-03-05 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-05 Thread Jos van Uden

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 {
  ...
}


Re: A little of coordination for Rosettacode

2013-03-04 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-03-04 Thread Jos van Uden

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.



Re: A little of coordination for Rosettacode

2013-03-04 Thread Jos van Uden

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.
 



Re: A little of coordination for Rosettacode

2013-03-04 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-04 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-04 Thread Jos van Uden

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.




Re: A little of coordination for Rosettacode

2013-03-04 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-03-04 Thread bearophile
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


Re: A little of coordination for Rosettacode

2013-02-27 Thread FG

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.




Re: A little of coordination for Rosettacode

2013-02-27 Thread FG

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[]);



Re: A little of coordination for Rosettacode

2013-02-27 Thread bearophile

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


Re: A little of coordination for Rosettacode

2013-02-26 Thread bearophile

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


  1   2   >