Re: unicode console output

2014-04-02 Thread Jos van Uden

On 2-4-2014 15:38, Denis Mezhov wrote:

On Wednesday, 2 April 2014 at 12:51:57 UTC, bearophile wrote:

Denis Mezhov:


How to out unicode cyrillic string to console?


Try this command on the command line:

chcp 65001

Bye,
bearophile


chcp 65001 dont'work


start.bat

mode con cols=150 lines=50
chcp 65001
%Path%\Minesweeper\Debug\Mi.exe

don't out correct string


Do you have a Unicode font selected in the dosbox properties,
like Lucida Console ?


Re: How to foreach over a DList?

2014-03-31 Thread Jos van Uden

On 31-3-2014 19:50, Jeroen Bollen wrote:

I am trying to foreach over a std.container.DList but it isn't working. I have 
tried the following code: https://gist.github.com/Binero/f30e56351baf05f1a2ec

I am getting the following errors:

/usr/include/dlang/dmd/std/container.d(1925): Error: template 
std.container.DList!ubyte.DList.insertBeforeNode cannot deduce function from 
argument types !()(typeof(null), int), candidates are:
/usr/include/dlang/dmd/std/container.d(2096): 
std.container.DList!ubyte.DList.insertBeforeNode(Stuff)(Node* n, Stuff stuff) if 
(isInputRange!Stuff  isImplicitlyConvertible!(ElementType!Stuff, T))
/usr/include/dlang/dmd/std/container.d(2155): 
std.container.DList!ubyte.DList.insertBeforeNode(Stuff)(Node* n, Stuff stuff) 
if (isImplicitlyConvertible!(Stuff, T))
source/app.d(7): Error: template instance 
std.container.DList!ubyte.DList.insertBack!int error instantiating
source/app.d(11): Error: invalid foreach aggregate list1


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


Re: Sorting with non-ASCII characters

2013-09-24 Thread Jos van Uden

On 24-9-2013 11:26, Chris wrote:

On Thursday, 19 September 2013 at 18:44:54 UTC, Jos van Uden wrote:

On 19-9-2013 17:18, Chris wrote:

Short question in case anyone knows the answer straight away:

How do I sort text so that non-ascii characters like á are treated in the same way as 
a?

Now I'm getting this:

[wow, ara, ába, marca]

=== sort(listAbove);

[ara, marca, wow, ába]

I'd like to get:

[ ába, ara, marca, wow]


If you only need to process extended ascii, then you could perhaps
make do with a transliterated sort, something like:

import std.stdio, std.string, std.algorithm, std.uni;

void main() {
auto sa = [wow, ara, ába, Marca];
writeln(sa);
trSort(sa);
writeln(sa);
}

void trSort(C, alias less = a  b)(C[] arr) {
static dstring c1 = àáâãäåçèéêëìíîïñòóôõöøùúûüýÿ;
static dstring c2 = aacnooyy;
schwartzSort!(a = tr(toLower(a), c1, c2), less)(arr);
}


Thanks a million, Jos! This does the trick for me.


Great.

Be aware that the above code does a case insensitive sort, if you need
case sensitive, you can use something like:


import std.stdio, std.string, std.algorithm, std.uni;

void main() {
auto sa = [wow, ara, ába, Marca];
writeln(sa);
trSort(sa, CaseSensitive.no);
writeln(sa);

writeln;

sa = [wow, ara, ába, Marca];

writeln(sa);
trSort(sa, CaseSensitive.yes);
writeln(sa);
}

void trSort(C, alias less = a  b)(C[] arr,
CaseSensitive cs = CaseSensitive.yes) {

static c1 = àáâãäåçèéêëìíîïñòóôõöøùúûüýÿÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝŸd;

static c2 = aacnooyyAACNOOYYd;

if (cs == CaseSensitive.no)

arr.schwartzSort!(a = a.toLower.tr(c1, c2), less);
else
arr.schwartzSort!(a = a.tr(c1, c2), less);
}


Re: Sorting with non-ASCII characters

2013-09-19 Thread Jos van Uden

On 19-9-2013 17:18, Chris wrote:

Short question in case anyone knows the answer straight away:

How do I sort text so that non-ascii characters like á are treated in the same way as 
a?

Now I'm getting this:

[wow, ara, ába, marca]

=== sort(listAbove);

[ara, marca, wow, ába]

I'd like to get:

[ ába, ara, marca, wow]


If you only need to process extended ascii, then you could perhaps
make do with a transliterated sort, something like:

import std.stdio, std.string, std.algorithm, std.uni;

void main() {
auto sa = [wow, ara, ába, Marca];
writeln(sa);
trSort(sa);
writeln(sa);
}

void trSort(C, alias less = a  b)(C[] arr) {
static dstring c1 = àáâãäåçèéêëìíîïñòóôõöøùúûüýÿ;
static dstring c2 = aacnooyy;
schwartzSort!(a = tr(toLower(a), c1, c2), less)(arr);
}



Re: Iterate over a string to get unicode codes

2013-09-01 Thread Jos van Uden

On 1-9-2013 16:11, Adam D. Ruppe wrote:

On Sunday, 1 September 2013 at 14:07:00 UTC, Flamaros wrote:

Is there a simple way to extract from a string all Unicode codes as uint values?


string foo = whatever;

foreach(dchar ch; foo) {
// ch is the code point as a 32 bit number
// use it directly or cast to uint here
}


Or, if you prefer one-liners.

import std.stdio, std.string, std.conv;

void main() {
auto s = \u00A0\u2345\u7865;
dtext(s).representation.writeln;
}




Re: Code from a Rosetta Code Task

2013-08-30 Thread Jos van Uden

On 30-8-2013 0:40, H. S. Teoh wrote:
(...)

A far better implementation is to use std.range.recurrence:

uint fib(in uint n) pure nothrow {
return recurrence!((a,n) = a[n-2] + a[n-1])(1, 1)
.drop(n-1)
.front;
}

This implementation has linear time complexity and constant space
complexity (vs. exponential time complexity vs. linear space complexity
in the original).

To illustrate how bad it is, I wrote a program that calls fib(50) for
each of the above implementations, and observed how long it takes each
one to return an answer. The version using recurrence completes in a
fraction of a second, the second takes two *minutes*. I bumped it up to
fib(100), and the recurrence version still runs under a fraction of a
second, but I ran out of patience waiting for the second one.


(...)

http://www.wolframalpha.com/input/?i=fib(100)


void main() {
import std.bigint, std.range;
BigInt fib(in uint fibN) pure {
return recurrence!((a,n) = a[n-2] + a[n-1])(BigInt(1), BigInt(1))
.drop(fibN-1)
.front;
}
assert(fib(100) == BigInt(354_224_848_179_261_915_075));
}


nice



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-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-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-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-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 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 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 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: gui libs

2013-03-01 Thread Jos van Uden

On 1-3-2013 10:03, thedeemon wrote:

On Thursday, 28 February 2013 at 09:35:03 UTC, rho wrote:

hi,
what keeps me from using d, is that there is no compilable gui lib available. 
does dfl compile with the latest dmd?


I am using DFL successfully with DMD 2.062. One just needs to take sources from 
here:
https://github.com/Rayerd/dfl
Set correct path to dmd in makelib.bat, then run go.bat.
It compiles fine with DMD 2.060, but 2.061 and later complain about a place in
environment.d where a couple of goto case should be added. With this little 
change DFL builds fine and works well.


I wish we had std.gui

And std.audio as well for that matter. Or std.media. Something like that.


Re: A little of coordination for Rosettacode

2013-02-26 Thread Jos van Uden

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.


Re: A little of coordination for Rosettacode

2013-02-25 Thread Jos van Uden

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.




Re: A little of coordination for Rosettacode

2013-02-25 Thread Jos van Uden

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 :)



Re: A little of coordination for Rosettacode

2013-02-22 Thread Jos van Uden

Somebody added an incorrect notice to the D entry for Dijkstra's algorithm.
http://rosettacode.org/mw/index.php?title=Dijkstra%27s_algorithmdiff=nextoldid=147068


Re: A little of coordination for Rosettacode

2013-02-19 Thread Jos van Uden

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


Re: A little of coordination for Rosettacode

2013-02-16 Thread Jos van Uden

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




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

2013-02-16 Thread Jos van Uden

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!


Re: A little of coordination for Rosettacode

2013-02-16 Thread Jos van Uden

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.



Re: A little of coordination for Rosettacode

2013-02-16 Thread Jos van Uden

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?



Re: A little of coordination for Rosettacode

2013-02-15 Thread Jos van Uden

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



Ping qznc: Re: A little of coordination for Rosettacode

2013-02-15 Thread Jos van Uden

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



 



Re: A little of coordination for Rosettacode

2013-02-11 Thread Jos van Uden

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




Re: Creating an array of default-constructed class instances

2013-02-10 Thread Jos van Uden

On 10-2-2013 7:14, Simon wrote:

Hi, I'm new to the D programming language.  Overall I'm liking
things very much, but I'm still getting the hang of a few things.

Here's a basic programming pattern: I have a class called Thing,
and while I'm coding I decide I need N Thing instances.

In C++ that's a matter of

std::vectorThing things(N);

In python, I can use a list comprehension.

things = [Thing() for _ in range(N)]

However, the obvious D version doesn't work.

auto things = new Thing[N];

Because Thing.init is null, this produces an array of null
references.  Of course, I can write a for loop to fill in the
array after creation, but this feels very un-D-like.  Is there a
straightforward way to create a bunch of class instances?


import std.stdio, std.algorithm;

class Thing {
int i;
this(int i) {
this.i = i;
}
}

void main()
{
   auto things = new Thing[10];
   fill(things, new Thing(5));

   foreach (t; things)
writef(%d , t.i);
}


Re: A little of coordination for Rosettacode

2013-02-09 Thread Jos van Uden

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.


Re: A little of coordination for Rosettacode

2013-02-05 Thread Jos van Uden

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







Re: A little of coordination for Rosettacode

2013-02-05 Thread Jos van Uden

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




Re: Regarding isSorted

2013-02-05 Thread Jos van Uden

On 6-2-2013 1:33, bearophile wrote:



Maybe this line:

https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm.d#L9237

 for (; !ahead.empty; ahead.popFront(), ++i)

Should be:

 for (; !ahead.empty; ahead.popFront(), r.popFront(), ++i)



Thought that line looked fishy. But I don't understand half the code in Phobos 
so I
figured it must be me...



Re: Simple operator precidence chart (and associativity)?

2012-03-14 Thread Jos van Uden

On 14-3-2012 0:14, Timon Gehr wrote:

I don't think there is, but I think I can create one:

! // 1 template instantiation
= // 2 goesto, binds weaker to the right
. ++ -- ( [ // 3 postfix operators
^^ // 4 power (right-associative)
 ++ -- * - + ! ~ // 5 prefix operators
* / % // 6 multiplicative operators
+ - ~ // 7 additive operators
// 8 shift operators
== !=   = = \ // 9 relational operators
! ! != != \
! = != in \
!in is !is
 // 10 bitwise AND (ambiguous with 9)
^ // 11 bitwise XOR (ambiguous with 9)
| // 12 bitwise OR (ambiguous with 9)
 // 13 logical AND
|| // 14 logical OR
?: // 15 conditional operator
/= = |= -= += \ // 16 assignment operators (right-associative)
= = = = \
*= %= ^= ^^= ~=
= // 17 goesto, binds stronger to the left
, // 18 comma operator
.. // range (not actually an operator)


The TDPL has a list of expressions in decreasing precedence
on pages 61-63. Some of these operators, like  or ^^= are
not listed there.

Is there a difference between != and  ?

Why is the goesto operator listed twice? Is that accidental?

Jos







comma inside is expression

2012-03-14 Thread Jos van Uden

I've been reading the tutorial on templates and found this example:

template rank(T)  {
static if (is(T t == U[], U)) // is T an array of U, for some type U?
enum rank = 1 + rank!(U); // then let’s recurse down.
else
enum rank = 0; // Base case, ending the recursion.
}


TDPL never mentions the use of a comma operator inside an is
expression. Is this an undocumented feature? Also the symbol
't' is never used, but if I remove it, it won't compile.

It's a really good tutorial, but I find this particular example
puzzling.

Jos


Re: passing a string with the character as an argument

2012-02-28 Thread Jos van Uden

On 29-2-2012 7:06, James Miller wrote:

On 29 February 2012 18:51, jiccabr...@wrc.xerox.com  wrote:


Greetings!

I have this program,

import std.process : system;
import std.stdio;
int main(char[][] args)
{
  char[] cmd;

  for (int i=1;iargs.length;i++)
  {
cmd ~= args[i] ~  ;
  }
  writefln(cmd);
  return(1);
}

if I compile it and run it this way,

test 1! 2@ 3  4#

the result is




If you are on Windows, then I don't know why this is happening.


On windows the ampersand also has a special meaning. In that case
try the carrot ^ to escape

test 1! 2@ 3^  4#

Jos



Re: How to reverse char[]?

2012-02-08 Thread Jos van Uden

On 8-2-2012 2:36, Timon Gehr wrote:


char[] is handled by Phobos as a range of dchar, ergo it does not have
swappable elements.


I'm surprised that array.reverse does work (using 2.057)



Re: tiny web server in D

2011-07-13 Thread Jos van Uden

On 14-7-2011 5:48, Dr.Smith wrote:

import std.socket, std.string;

void main() {
 Socket listener = new TcpSocket;
 assert(listener.isAlive);
 listener.bind(new InternetAddress(8080));
 listener.listen(10);
 string webpage = index.html;

 Socket currSock;
 uint bytesRead;
 ubyte buff[1];

 while(1) {
 currSock = listener.accept();
 while ((bytesRead = currSock.receive(buff))  0) {
currSock.sendTo(webpage);
 }
 currSock.close();
 buff.clear();
 }
}


I recieve

index.htmlindex.htmlindex.html etc etc

if I use this, it works

import std.socket, std.string;

void main() {
Socket listener = new TcpSocket;
assert(listener.isAlive);
listener.bind(new InternetAddress(8080));
listener.listen(10);
string webpage = htmlbodyhi/body/html;

Socket currSock;
uint bytesRead;
ubyte buff[1];

while(1) {
currSock = listener.accept();
if ((bytesRead = currSock.receive(buff))  0) {
   currSock.sendTo(webpage);
}
currSock.close();
buff.clear();
}
}


Re: enum sstring problem

2011-06-15 Thread Jos van Uden

Using 2.053 on win32 (XP), compiles and runs.


Re: x has forward references

2009-08-16 Thread Jos van Uden
Jacob Carlborg Wrote:

 It works with dmd 1.045

Where to get it?

I also tried compiling derelict today. I finally managed to get past the error 
messages by using the dmd compiler that ships with tango. 1.033 if I remember 
correctly. The lib folder filled up nicely with files. Then I did a dsss 
install command. The libs now show up in the dsss/lib folder and there are .di 
files in the include/derelict folder.

So I tried to compile a little test.d

module derelicttest;

import derelict.opengl.gl;

void main()
{
DerelictGL.load();
}

The dsss.conf:

[*]
buildflags = -g -gc

[test.d]


I don't know what else to put in there. I'm compiling with dmd 1.046. And get 
the following message.

D:\Workshop\D\derelictdsss build
test.d = test
OPTLINK (R) for Win32  Release 8.00.1
Copyright (C) Digital Mars 1989-2004  All rights reserved.
D:\Workshop\D\dsss\lib\\DerelictGL.lib(gl)
 Error 42: Symbol Undefined _D6object9Exception5_ctorMFAaC9ExceptionZC9Exception
--- errorlevel 1
Command D:\Workshop\D\dsss\bin\rebuild.exe returned with code -1, aborting.
Error: Command failed, aborting.

If I try it with the 1.033 compiler that ships with tango the list of messages 
is similar but even longer.








Re: x has forward references

2009-08-16 Thread Jos van Uden
Spacen Jasset Wrote:

 Jos van Uden wrote:
  Jacob Carlborg Wrote:
  
  On 8/16/09 19:36, Jos van Uden wrote:
  Jacob Carlborg Wrote:
 
  It works with dmd 1.045
  Where to get it?
  http://www.digitalmars.com/d/1.0/changelog.html#new1_045
  
  Thank you. This version does indeed compile the libs, just like 1.033, but 
  I still get the same error when I try to compile the test. When I do the 
  DerelictAL test (alinfo) that comes with the derelict download, it compiles 
  and runs just fine.
  
  
 Try zapping all the derelict object and lib files.

That did the trick. Thanks.


calling function templates

2009-08-09 Thread Jos van Uden

I noticed that I don't always have to use the bang notation for
function templates. I played around with that a little, but got
an error when I used a static array. I think it's because of a
casting problem or wrong type inference... I don't imagine it's
a bug. Just not possible.

module test;

import std.range;

void putNumbers(Range, T)(Range r, T start, T incr) {
T i = start;
while (!r.empty) {
r.put(i);  // line 8
i += incr;
}
}

void main() {

int[] arr = new int[20];
putNumbers!(int[])(arr, 0, 3); // dyn array, bang notation

int[] arr2 = new int[20];
putNumbers(arr2, 0, 3); // dyn array, regular notation

int[20] arr3;
putNumbers!(int[])(arr3, 0, 3); // stat array, bang notation

int[20] arr4;
putNumbers(arr4, 0, 3); // ERROR, stat array, regular notation

}

test.d(8): Error: cast(int[])r is not an lvalue
test.d(25): Error: template instance test.putNumbers!(int[20u],int) 
error instantiating


Re: calling function templates

2009-08-09 Thread Jos van Uden

bearophile wrote:

And a more general note Jos van Uden: don't use D2, it's unfinished, things 
don't work yet. Use a stable version of D1, like 1.042.

Bye,
bearophile


I'm not using the language. Just trying to learn it. Most code
examples I see, require D2.

Jos


Re: how does range.put work

2009-08-08 Thread Jos van Uden

Oliver wrote:

The source code for the standard library comes with the compiler.
If you look in std\array.d, you find this around line 279 (reflowed for
readability):

void put(T, E)(ref T[] a, E e) {
assert(a.length);
a[0] = e; a = a[1 .. $];
}


Would anybody care to explain what this is used for? I find
the example in array.d rather unhelpful.

Example:

void main()
{
int[] a = [ 1, 2, 3 ];
int[] b = a;
a.put(5);
assert(a == [ 2, 3 ]);
assert(b == [ 5, 2, 3 ]);
}

You're putting an element in a, but then the first element is moved out 
of a and the new one shows up in b? Weird. I guess I don't understand 
what a range is.


Jos




Re: how does range.put work

2009-08-08 Thread Jos van Uden

Daniel Keep wrote:


No; read the code.  Before the put, a and b are pointing to the same
span of memory.  a.put(5) puts the value 5 into the front (first
element) of the array, then advances the array.

However, put can't see b, so it doesn't get updated along with a.  The
end result is that b = [5,2,3] and a = b[1..3] = [2,3].

Why do it like this?  Here's an example:

void putNumbers(Range)(Range r)
{
int i = 0;
while( !r.empty )
{
r.put(i);
++i;
}
}

void main()
{
int[10] ten_numbers;
putNumbers(ten_numbers);
assert( ten_numbers = [0,1,2,3,4,5,6,7,8,9] );
}


I see.

Your example should be in the documentation in my opinion, rather
then the meaningless one that's there now. Something like this
perhaps:

void putNumbers(Range, T)(Range r, T start, T incr) {
T i = start;
while( !r.empty )
{
r.put(i);
i += incr;
}
}

void main() {
   int[10] ten_ints;
   putNumbers!(int[])(ten_ints, 4, 2);
   assert( ten_ints == [4,6,8,10,12,14,16,18,20,22] );
}

Jos