Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread rikki cattermole via Digitalmars-d-learn



On 30/08/2022 8:16 AM, Gavin Ray wrote:

It must have been the "writing at end of file" bit?


I don't know.

It read like it should work.

The offsets were correct, it just didn't work *shrug*.


Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread Gavin Ray via Digitalmars-d-learn

On Monday, 29 August 2022 at 15:52:31 UTC, rikki cattermole wrote:
After a bunch of playing around I managed to determine that it 
is as simple as the mode.


exists(dbFileName) ? "r+" : "w+"



Will fix it.

Of course you shouldn't delete the file like that method is 
doing. It should probably reinitialize the FILE* descriptor.


D'oh!

I didn't even think about the mode:

  > `a+ or ab+ or a+b`
  > "Append; open or create file for update, writing at 
end-of-file."


It must have been the "writing at end of file" bit?

Thanks Rikki. /embarrassed


Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread ag0aep6g via Digitalmars-d-learn

On Monday, 29 August 2022 at 16:21:53 UTC, ag0aep6g wrote:
You never change `pageId`. So as far as I can tell, you're 
always `seek`-ing to the same position, and you just overwrite 
the same piece of the file again and again.


Whoops. I guess I missed the point of the question there.


Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread ag0aep6g via Digitalmars-d-learn

On Sunday, 28 August 2022 at 22:46:17 UTC, Gavin Ray wrote:

I've put the code, stripped to a minimal example here:
- https://ldc.godbolt.org/z/fzsx3Tnnn

[...]


But if the same code is placed inside of a `for` loop, suddenly 
no writes occur:

[...]


Does anyone know what is happening here? It's really puzzling.


Relevant pieces of the code:

```d
class DiskManager
{
void writePage(PageId pageId, ubyte[PAGE_SIZE] pageData)
{
synchronized (dbIOMutex.writer)
{
dbFile.seek(pageId * PAGE_SIZE);
dbFile.rawWrite(pageData);
}
}
}

void singleReadWrite()
{
PageId pageId = 0;

diskManager.writePage(pageId, pageData);
}

void multiReadWrite()
{
PageId pageId = 0;

foreach (i; 0 .. 10)
{
diskManager.writePage(pageId, pageData);
}
}
```

You never change `pageId`. So as far as I can tell, you're always 
`seek`-ing to the same position, and you just overwrite the same 
piece of the file again and again.


Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread rikki cattermole via Digitalmars-d-learn
After a bunch of playing around I managed to determine that it is as 
simple as the mode.


exists(dbFileName) ? "r+" : "w+"



Will fix it.

Of course you shouldn't delete the file like that method is doing. It 
should probably reinitialize the FILE* descriptor.


Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread Gavin Ray via Digitalmars-d-learn

On Monday, 29 August 2022 at 07:04:49 UTC, bauss wrote:

Does anyone know what is happening here? It's really puzzling.


You probably need to flush the output.


That's a good idea. I gave it a shot, and the following doesn't 
seem to change anything unfortunately:


```d
void writePage(PageId pageId, ubyte[PAGE_SIZE] pageData)
{
synchronized (dbIOMutex.writer)
{
dbFile.seek(pageId * PAGE_SIZE);
dbFile.rawWrite(pageData);
dbFile.flush();
dbFile.sync();
}
}
```


Re: Disk write in a "for" loop with RwMutex never happens

2022-08-29 Thread bauss via Digitalmars-d-learn

On Sunday, 28 August 2022 at 22:46:17 UTC, Gavin Ray wrote:

I've put the code, stripped to a minimal example here:
- https://ldc.godbolt.org/z/fzsx3Tnnn

You can see that the single write + read version of the code 
works just fine:

```
pageData[0..4] = [1, 2, 3, 4]
readData[0..4] = [1, 2, 3, 4]
```

Where here, `pageData` is the data to be written to a file, and 
`readData` is the result of trying to read the freshly written 
file data.


But if the same code is placed inside of a `for` loop, suddenly 
no writes occur:

```d
pageData[0..4] = [0, 0, 0, 0]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 1]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 2]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 3]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 4]
readData[0..4] = [0, 0, 0, 0]

// ...
```

Does anyone know what is happening here? It's really puzzling.


You probably need to flush the output.


Disk write in a "for" loop with RwMutex never happens

2022-08-28 Thread Gavin Ray via Digitalmars-d-learn

I've put the code, stripped to a minimal example here:
- https://ldc.godbolt.org/z/fzsx3Tnnn

You can see that the single write + read version of the code 
works just fine:

```
pageData[0..4] = [1, 2, 3, 4]
readData[0..4] = [1, 2, 3, 4]
```

Where here, `pageData` is the data to be written to a file, and 
`readData` is the result of trying to read the freshly written 
file data.


But if the same code is placed inside of a `for` loop, suddenly 
no writes occur:

```d
pageData[0..4] = [0, 0, 0, 0]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 1]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 2]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 3]
readData[0..4] = [0, 0, 0, 0]

pageData[0..4] = [0, 0, 0, 4]
readData[0..4] = [0, 0, 0, 0]

// ...
```

Does anyone know what is happening here? It's really puzzling.


Re: Printing Tuple!(...)[] using for loop?

2021-07-02 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/2/21 12:21 AM, Kirill wrote:
I have a `Tuple!(string, ..., string)[] data` that I would like to print 
out:

`a   b   c`
`1   2   3`
`4   5   6`

     Furthermore, I want to be able to print any N rows and M columns of 
that table. For instance:

     `b   c`
     `2   3`
     or
     `1   2   3`
     `4   5   6`

I am using for loops for that:

     // inside some function(rows, cols):
     immutable startFromRow = ...;
     immutable endWithRow = ...;
     immutable startFromCol = ...;
     immutable endWithCol = ...;

     // print data
     for(size_t i = startFromRow; i < endWithRow; i++) {
     for(size_t j = startFromCol; j < endWithCol; j++) {
     writef("%s", data[i][j]);
     }
     writef("\n");
     }

And the compiler puts out the following:
`Error: variable 'j' cannot be read at compile time`

I tried `data[i].expand[j]`, but the same error occurs anyway.

I have two questions:
1. How do I print the contents of a Tuple using for loops? Or any other 
method?

2. What am I missing? How does it actually work under the hood?


So a tuple is really like an unnamed group of variables.

A `Tuple!(int, int, int)` is really like three ints that are all 
separate variables. It's just that they are named via the group. It is 
NOT like an array, it's more like a struct with fields that have indexes 
instead of names.


In order to print them in a loop, based on *runtime* data, you need to 
bridge the gap between runtime and compile time. Why? Because a Tuple 
does not necessarily contain the same types for every value, so `tup[0]` 
might have a different type than `tup[1]`. Because D is strongly-typed, 
you need to access these with *compile-time* indexes, so it knows what 
type you are using.


Imagine you have a struct, and you want to use a runtime string to 
access a given field. This is essentially the same, except it's an index 
and not a name.


A typical way to bridge the gap is to use a switch to validate the 
runtime variable, and then use the compile-time equivalalent to actually 
get the data.


For example, you could write a function like:

```d
void printItem(Tuple!(...) vals, size_t index)
{
theswitch:
final switch(index)
{
   static foreach(ctIdx; 0 .. vals.length) {
case ctIdx: writeln(vals[ctIdx]);
break theswitch;
   }
}
}
```

Now, if you want to just print them in order, without any runtime 
details, you can just use foreach on a tuple and it works (the foreach 
variables are compile-time determined).


-Steve


Re: Printing Tuple!(...)[] using for loop?

2021-07-02 Thread Bastiaan Veelo via Digitalmars-d-learn

On Friday, 2 July 2021 at 04:21:24 UTC, Kirill wrote:

I have a `Tuple!(string, ..., string)[] data`


If there are only strings in the tuple, it could be simplified by 
making it a static array of strings instead. The compile-time 
index issue would go away.


—Bastiaan


Re: Printing Tuple!(...)[] using for loop?

2021-07-02 Thread Alexandru Ermicioi via Digitalmars-d-learn

On Friday, 2 July 2021 at 04:21:24 UTC, Kirill wrote:

...


1. use static foreach for tuple loop.
2. start column and end column should be known at compile time. 
Either make them immutable, or as enum constant, or pass them as 
an template argument.


Tuple is basically a wrapper over built in tuple support from D. 
Check it's insides to se how it is done. So to index a field in a 
tuple you need to know which field you want to access at compile 
time since, each field in a tuple has different size, and cannot 
be indexed at runtime easily.


Best regards,
Alexandru.


Printing Tuple!(...)[] using for loop?

2021-07-01 Thread Kirill via Digitalmars-d-learn
I have a `Tuple!(string, ..., string)[] data` that I would like 
to print out:

`a   b   c`
`1   2   3`
`4   5   6`

Furthermore, I want to be able to print any N rows and M 
columns of that table. For instance:

`b   c`
`2   3`
or
`1   2   3`
`4   5   6`

I am using for loops for that:

// inside some function(rows, cols):
immutable startFromRow = ...;
immutable endWithRow = ...;
immutable startFromCol = ...;
immutable endWithCol = ...;

// print data
for(size_t i = startFromRow; i < endWithRow; i++) {
for(size_t j = startFromCol; j < endWithCol; j++) {
writef("%s", data[i][j]);
}
writef("\n");
}

And the compiler puts out the following:
`Error: variable 'j' cannot be read at compile time`

I tried `data[i].expand[j]`, but the same error occurs anyway.

I have two questions:
1. How do I print the contents of a Tuple using for loops? Or any 
other method?

2. What am I missing? How does it actually work under the hood?

Thanks in advance. Any help is greatly appreciated.




Re: preset counter variable in a for loop

2020-02-28 Thread Namal via Digitalmars-d-learn

On Friday, 28 February 2020 at 12:48:17 UTC, mipri wrote:

On Friday, 28 February 2020 at 12:44:52 UTC, Namal wrote:

Hello,

I don't understand why this simple code causes a compiler 
error..


import std.stdio;

void main(){

 int b = 0;

 for (b; b<3; b++){
   writeln(b);  
 }
}

$Error: b has no effect


Well, that's the error. b has no effect, so there's
no need for it, and it's likely written in error. It
has no effect in C++ either, and you may get a warning:

example.cc: In function 'int main()':
example.cc:7:8: warning: statement has no effect 
[-Wunused-value]

  for (b; b<3; b++){


Thanks, I didn't know that you don't need it there and can leave 
it out!




Re: preset counter variable in a for loop

2020-02-28 Thread mipri via Digitalmars-d-learn

On Friday, 28 February 2020 at 12:44:52 UTC, Namal wrote:

Hello,

I don't understand why this simple code causes a compiler 
error..


import std.stdio;

void main(){

 int b = 0;

 for (b; b<3; b++){
   writeln(b);  
 }
}

$Error: b has no effect


Well, that's the error. b has no effect, so there's
no need for it, and it's likely written in error. It
has no effect in C++ either, and you may get a warning:

example.cc: In function 'int main()':
example.cc:7:8: warning: statement has no effect [-Wunused-value]
  for (b; b<3; b++){



preset counter variable in a for loop

2020-02-28 Thread Namal via Digitalmars-d-learn

Hello,

I don't understand why this simple code causes a compiler error..

import std.stdio;

void main(){

 int b = 0;

 for (b; b<3; b++){
   writeln(b);  
 }
}

$Error: b has no effect

Same works perfectly fine in C++

#include 

int main(){
 int i = 0;

 for(i; i<3; i++)
   std::cout<

Re: preset counter variable in a for loop --> 'has no effect' Error

2020-02-28 Thread drug via Digitalmars-d-learn

On 2/28/20 11:48 AM, Namal wrote:

Hello,

I don't understand why this simple code causes a compiler error..

import std.stdio;

void main(){

  int b = 0;

  for (b; b<3; b++){
    writeln(b);
  }
}

$Error: b has no effect

Same works perfectly fine in C++

#include 

int main(){
  int i = 0;

  for(i; i<3; i++)
    std::cout<

D compiler is smart enough to say that the first use of `b` in for loop 
is useless. Use either this variant:

```
import std.stdio;

void main(){

 int b = 0;

 for (; b<3; b++){
   writeln(b);
 }
}
```
or this:
```
import std.stdio;

void main(){

 for (int b; b<3; b++){
   writeln(b);
 }
}
```


preset counter variable in a for loop --> 'has no effect' Error

2020-02-28 Thread Namal via Digitalmars-d-learn

Hello,

I don't understand why this simple code causes a compiler error..

import std.stdio;

void main(){

 int b = 0;

 for (b; b<3; b++){
   writeln(b);  
 }
}

$Error: b has no effect

Same works perfectly fine in C++

#include 

int main(){
 int i = 0;

 for(i; i<3; i++)
   std::cout<

Re: For loop with separator

2019-07-06 Thread a11e99z via Digitalmars-d-learn

On Saturday, 6 July 2019 at 11:48:42 UTC, berni wrote:

On Thursday, 4 July 2019 at 17:00:33 UTC, Q. Schroll wrote:
The prime example is printing the comma when printing a list: 
There is one between any two elements, but neither is one at 
front or behind the last one.


If it is just for printing commas in between, you can use 
range.join(", ")


https://dlang.org/phobos/std_array.html#.join


.map!(e=>e.text).join( ", "); // map for non strings
or
.format!"%(%s, %)"; // for anything


Re: For loop with separator

2019-07-06 Thread berni via Digitalmars-d-learn

On Thursday, 4 July 2019 at 17:00:33 UTC, Q. Schroll wrote:
The prime example is printing the comma when printing a list: 
There is one between any two elements, but neither is one at 
front or behind the last one.


If it is just for printing commas in between, you can use 
range.join(", ")


https://dlang.org/phobos/std_array.html#.join




Re: For loop with separator

2019-07-04 Thread Alex via Digitalmars-d-learn

On Thursday, 4 July 2019 at 17:00:33 UTC, Q. Schroll wrote:

Probably you've come over this problem once in a while, too.
You have a repeating solution, so you use a for(each) loop.
Sometimes, there is an action to be performed between the end 
of one iteration and the beginning of the next, if there is 
one. The prime example is printing the comma when printing a 
list: There is one between any two elements, but neither is one 
at front or behind the last one.


Typical solutions I employed were:
1 Handling the first element separately
2 Condition in the loop, that is false exactly for the first 
iteration.


1 can be done with ranges easily:

if (!range.empty)
{
action(range.front);
range.popFront;
foreach (element; range)
{
betweenAction();
action(element);
}
}

This approach is clearly quite verbose for the problem, but 
there's nothing done unnecessarily.


2 can be done easily, too:

foreach (i, element; range)
{
if (i > 0) betweenAction();
action(element);
}

While 2 is less code, it's prone to be checked every iteration.
Note that 2 is rather D specific in its length. It can be done 
in other languages, but is more verbose.


Is there a cleaner solution that I missed?


As far as I can interpret it, joiner

https://dlang.org/library/std/algorithm/iteration/joiner.html

uses roughly the first approach.


For loop with separator

2019-07-04 Thread Q. Schroll via Digitalmars-d-learn

Probably you've come over this problem once in a while, too.
You have a repeating solution, so you use a for(each) loop.
Sometimes, there is an action to be performed between the end of 
one iteration and the beginning of the next, if there is one. The 
prime example is printing the comma when printing a list: There 
is one between any two elements, but neither is one at front or 
behind the last one.


Typical solutions I employed were:
1 Handling the first element separately
2 Condition in the loop, that is false exactly for the first 
iteration.


1 can be done with ranges easily:

if (!range.empty)
{
action(range.front);
range.popFront;
foreach (element; range)
{
betweenAction();
action(element);
}
}

This approach is clearly quite verbose for the problem, but 
there's nothing done unnecessarily.


2 can be done easily, too:

foreach (i, element; range)
{
if (i > 0) betweenAction();
action(element);
}

While 2 is less code, it's prone to be checked every iteration.
Note that 2 is rather D specific in its length. It can be done in 
other languages, but is more verbose.


Is there a cleaner solution that I missed?


Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread Daniel Kozák via Digitalmars-d-learn

On Thursday, 23 May 2019 at 18:37:17 UTC, H. S. Teoh wrote:
On Thu, May 23, 2019 at 06:20:23PM +, kdevel via 
Digitalmars-d-learn wrote:

On Thursday, 23 May 2019 at 09:44:15 UTC, Cym13 wrote:

[...]

> To go fast, read/write bigger chunks.

Or use rawWrite instead of write (reduces the runtime to about 
1.6 s). When using write time is IMHO spent in unicode 
processing and/or locking. Or write more characters at a time. 
The code below takes 60 ms to complete.


If you're on Linux, writing a bunch of zeroes just to create a 
large file is a waste of time. Just use the kernel's sparse 
file feature:


https://www.systutorials.com/136652/handling-sparse-files-on-linux/

The blocks won't actually get allocated until you write 
something to them, so this beats any write-based method of 
creating a file filled with zeroes -- probably by several 
orders of magnitude. :-P



T


Yes using sparse files is good, but only for this case. If you 
need write something else than null it is not so usable. But 
AFAIK not all FS support this anyway


Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread Daniel Kozak via Digitalmars-d-learn
On Thu, May 23, 2019 at 11:06 PM Daniel Kozak  wrote:

> On Thu, May 23, 2019 at 11:10 AM BoQsc via Digitalmars-d-learn <
> digitalmars-d-learn@puremagic.com> wrote:
>

> https://matthias-endler.de/2017/yes/
>

So this should do it

void main()
{
import std.range : array, cycle, take;
import std.stdio;
immutable buf_size = 8192;
immutable buf = "\x00".cycle.take(buf_size).array;
auto cnt = 50_000_000 / buf_size;
immutable tail = "\x00".cycle.take(50_000_000 % buf_size).array;
File file = File("test.txt", "w");
while(cnt--)
file.rawWrite(buf);
file.rawWrite(tail);
}


Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread Daniel Kozak via Digitalmars-d-learn
On Thu, May 23, 2019 at 11:19 PM Daniel Kozak  wrote:

Fixed version without decode to dchar

void main()
{
import std.range : array, cycle, take;
import std.stdio;
import std.utf;
immutable buf_size = 8192;
immutable buf = "\x00".byCodeUnit.cycle.take(buf_size).array;
auto cnt = 50_000_000 / buf_size;
immutable tail = "\x00".byCodeUnit.cycle.take(50_000_000 %
buf_size).array;
File file = File("test.txt", "w");
while(cnt--)
file.rawWrite(buf);
file.rawWrite(tail);
}


Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread Daniel Kozak via Digitalmars-d-learn
On Thu, May 23, 2019 at 11:10 AM BoQsc via Digitalmars-d-learn <
digitalmars-d-learn@puremagic.com> wrote:

> This code of D creates a dummy 47,6 MB text file filled with Nul
> characters in about 9 seconds
>
> import std.stdio, std.process;
>
> void main() {
>
> writeln("Creating a dummy file");
> File file = File("test.txt", "w");
>
> for (int i = 0; i < 5000; i++)
> {
> file.write("\x00");
> }
> file.close();
>
> }
>
>
> While GNU coreutils dd can create 500mb dummy Nul file in a
> second.
> https://github.com/coreutils/coreutils/blob/master/src/dd.c
>
> What are the explanations for this?
>

https://matthias-endler.de/2017/yes/


Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread H. S. Teoh via Digitalmars-d-learn
On Thu, May 23, 2019 at 06:20:23PM +, kdevel via Digitalmars-d-learn wrote:
> On Thursday, 23 May 2019 at 09:44:15 UTC, Cym13 wrote:
[...]
> > To go fast, read/write bigger chunks.
> 
> Or use rawWrite instead of write (reduces the runtime to about 1.6 s).
> When using write time is IMHO spent in unicode processing and/or
> locking. Or write more characters at a time. The code below takes 60
> ms to complete.

If you're on Linux, writing a bunch of zeroes just to create a large
file is a waste of time. Just use the kernel's sparse file feature:

https://www.systutorials.com/136652/handling-sparse-files-on-linux/

The blocks won't actually get allocated until you write something to
them, so this beats any write-based method of creating a file filled
with zeroes -- probably by several orders of magnitude. :-P


T

-- 
It is not the employer who pays the wages. Employers only handle the money. It 
is the customer who pays the wages. -- Henry Ford


Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread kdevel via Digitalmars-d-learn

On Thursday, 23 May 2019 at 09:44:15 UTC, Cym13 wrote:

[...]

Note in particular the blocksize argument. I set it to 1M but 
by default it's 512 bytes. If you use strace with the command 
above you'll see a series of write() calls, each writting 1M of 
null bytes to testfile. That's the main difference between your 
code and what dd does: it doesn't write 1 byte at a time.


His code doesn't write 1 byte at a time either. strace on my 
machine reports
a blocksize of 4096. If I use this blocksize with dd it still 
takes only a fraction of a second to complete.


This results in way less system calls and system calls are very 
expensive.


His program and dd with bs=4K both have the same number of 
syscalls.



To go fast, read/write bigger chunks.


Or use rawWrite instead of write (reduces the runtime to about 
1.6 s). When using write time is IMHO spent in unicode processing 
and/or locking. Or write more characters at a time. The code 
below takes 60 ms to complete.


y.d
```
import std.stdio, std.process;

void main()
{
   writeln("Creating a dummy file");
   File file = File("test.txt", "w");
   ubyte [4096] nuls;

   for (int i = 0; i < 50_000_000 / nuls.sizeof; ++i)
  file.write(cast (char[nuls.sizeof]) nuls);
   file.close();
}
```




Re: Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread Cym13 via Digitalmars-d-learn

On Thursday, 23 May 2019 at 09:09:05 UTC, BoQsc wrote:
This code of D creates a dummy 47,6 MB text file filled with 
Nul characters in about 9 seconds


import std.stdio, std.process;

void main() {

writeln("Creating a dummy file");
File file = File("test.txt", "w");

   for (int i = 0; i < 5000; i++)
{
file.write("\x00");
}
   file.close();

}


While GNU coreutils dd can create 500mb dummy Nul file in a 
second.

https://github.com/coreutils/coreutils/blob/master/src/dd.c

What are the explanations for this?


If you're talking about benchmarking it's important to provide 
both source code and how you use/compile them. However in that 
case I think I can point you in the right direction already:


I'll suppose that you used something like that:

dd if=/dev/zero of=testfile bs=1M count=500

Note in particular the blocksize argument. I set it to 1M but by 
default it's 512 bytes. If you use strace with the command above 
you'll see a series of write() calls, each writting 1M of null 
bytes to testfile. That's the main difference between your code 
and what dd does: it doesn't write 1 byte at a time. This results 
in way less system calls and system calls are very expensive.


To go fast, read/write bigger chunks.

I may be wrong though, maybe you tested with a bs of 1 byte, so 
test for yourself and if necessary provide all informations and 
not just pieces so that we are able to reproduce your test :)


Why GNU coreutils/dd is creating a dummy file more efficiently than D's For loop?

2019-05-23 Thread BoQsc via Digitalmars-d-learn
This code of D creates a dummy 47,6 MB text file filled with Nul 
characters in about 9 seconds


import std.stdio, std.process;

void main() {

writeln("Creating a dummy file");
File file = File("test.txt", "w");

   for (int i = 0; i < 5000; i++)
{
file.write("\x00");
}
   file.close();

}


While GNU coreutils dd can create 500mb dummy Nul file in a 
second.

https://github.com/coreutils/coreutils/blob/master/src/dd.c

What are the explanations for this?


Re: Classes new'd inside for loop are all the same instance?

2016-09-08 Thread Meta via Digitalmars-d-learn

On Thursday, 8 September 2016 at 12:36:29 UTC, drug wrote:
&c is address of the variable c, that is allocated on the stack 
and has the same address on every iteration
cast(void*)c return the value of variable c that is address of 
a class instance and is different for every iteration


in other words
&c is address of pointer
cast(void*)c is the pointer itself


Yes, thank you. I'll just add that in D (as well as in Java and 
C#), while classes are always reference types and the type of `c` 
in `C c = new C();` will be reported as C, it's actually more of 
a hidden type, "reference to a C". These references are always 
passed by value.


c (reference to a C) value pointed at by c
on the stack  on the heap
[0x2450]...  [0x8695]
  |^
  ||


For example:

class C
{
string name;
}

void setName(C c)
{
c.name = "bob"; //This change will be seen outside setName
c = new C("jim"); //This change will not
}

void setNameRef(ref C c)
{
c.name = "bob"; //This change will be seen outside setNameRef
c = new C("jim"); //This change will also be seen outside 
setNameRef

}

In `setName` c (which is actually a reference to a C) cannot be 
rebound as the reference is passed by value into the function. 
However, c.name can still be modified as you are modifying the 
value pointed at by the reference, not the reference itself.


In `setNameRef` you can modify both, because c is passed by ref, 
meaning that there is now a double-indirection. Thus, you can 
modify both c and the value pointed at by c.


Re: Classes new'd inside for loop are all the same instance?

2016-09-08 Thread drug via Digitalmars-d-learn

08.09.2016 15:24, lobo пишет:

I am confused, which is normal, but I'd appreciate some help :-)

If I create N classes in a for loop they are all the same instance. I
would expect each to be a unique instance of the class. See the code below

---

class C {}
void main() {
import std.stdio;

auto c1 = new C();
writefln("c1:%s", &c1); // OK, instance c1 is unique

auto c2 = new C(); // OK, instance c2 is unqiue
writefln("c2:%s", &c2);

foreach(a; 0..10) {

C c = new C(); // All instances are the same object with the
same address?
writefln("c:%s", &c);

}
}
---

This isn't what I expected. What could I be doing wrong?

Thanks,
lobo


&c is address of the variable c, that is allocated on the stack and has 
the same address on every iteration
cast(void*)c return the value of variable c that is address of a class 
instance and is different for every iteration


in other words
&c is address of pointer
cast(void*)c is the pointer itself


Re: Classes new'd inside for loop are all the same instance?

2016-09-08 Thread lobo via Digitalmars-d-learn

On Thursday, 8 September 2016 at 12:36:29 UTC, drug wrote:

08.09.2016 15:24, lobo пишет:

[...]
&c is address of the variable c, that is allocated on the stack 
and has the same address on every iteration
cast(void*)c return the value of variable c that is address of 
a class instance and is different for every iteration


in other words
&c is address of pointer
cast(void*)c is the pointer itself


Got it, thank you :)


Re: Classes new'd inside for loop are all the same instance?

2016-09-08 Thread lobo via Digitalmars-d-learn

On Thursday, 8 September 2016 at 12:28:55 UTC, Meta wrote:

On Thursday, 8 September 2016 at 12:24:48 UTC, lobo wrote:

[...]


I don't have time to explain at the moment, but change the `&c` 
to `cast(void*)c` and you will see what you expect. I will post 
an explanation soon.


Thanks for the blazingly quick reply! :)

Please post the explanation when you get time because I'd love to 
know what is really happening.


bye,
lobo


Re: Classes new'd inside for loop are all the same instance?

2016-09-08 Thread rikki cattermole via Digitalmars-d-learn

On 09/09/2016 12:24 AM, lobo wrote:

I am confused, which is normal, but I'd appreciate some help :-)

If I create N classes in a for loop they are all the same instance. I
would expect each to be a unique instance of the class. See the code below

---

class C {}
void main() {
import std.stdio;

auto c1 = new C();
writefln("c1:%s", &c1); // OK, instance c1 is unique

auto c2 = new C(); // OK, instance c2 is unqiue
writefln("c2:%s", &c2);

foreach(a; 0..10) {

C c = new C(); // All instances are the same object with the
same address?
writefln("c:%s", &c);

}
}
---

This isn't what I expected. What could I be doing wrong?

Thanks,
lobo


Well for starters C is already a pointer ;)
cast(void*) should do the trick not &.



Re: Classes new'd inside for loop are all the same instance?

2016-09-08 Thread Meta via Digitalmars-d-learn

On Thursday, 8 September 2016 at 12:24:48 UTC, lobo wrote:

I am confused, which is normal, but I'd appreciate some help :-)

If I create N classes in a for loop they are all the same 
instance. I would expect each to be a unique instance of the 
class. See the code below


---

class C {}
void main() {
import std.stdio;

auto c1 = new C();
writefln("c1:%s", &c1); // OK, instance c1 is unique

auto c2 = new C(); // OK, instance c2 is unqiue
writefln("c2:%s", &c2);

foreach(a; 0..10) {

C c = new C(); // All instances are the same object 
with the same address?

writefln("c:%s", &c);

}
}
---

This isn't what I expected. What could I be doing wrong?

Thanks,
lobo


I don't have time to explain at the moment, but change the `&c` 
to `cast(void*)c` and you will see what you expect. I will post 
an explanation soon.


Classes new'd inside for loop are all the same instance?

2016-09-08 Thread lobo via Digitalmars-d-learn

I am confused, which is normal, but I'd appreciate some help :-)

If I create N classes in a for loop they are all the same 
instance. I would expect each to be a unique instance of the 
class. See the code below


---

class C {}
void main() {
import std.stdio;

auto c1 = new C();
writefln("c1:%s", &c1); // OK, instance c1 is unique

auto c2 = new C(); // OK, instance c2 is unqiue
writefln("c2:%s", &c2);

foreach(a; 0..10) {

C c = new C(); // All instances are the same object with 
the same address?

writefln("c:%s", &c);

}
}
---

This isn't what I expected. What could I be doing wrong?

Thanks,
lobo




Re: Regex match in for loop

2014-07-15 Thread Brad Anderson via Digitalmars-d-learn

On Tuesday, 15 July 2014 at 20:18:58 UTC, seany wrote:

Consider this:

import std.stdio, std.regex, std.array, std.algorithms ;

void main(string args[])
{

string[] greetings = ["hello", "hallo", "hoi", "salut"];

regex r = regex("hello", "g");

for(short i = 0; i < greetings.count(); i++)
{

  auto m = match(greetings[i], r);
}

}

To the best of my knowledge, declaring a variable inside a for 
loop is illegal, you can not delacre the same variable 
repeatedly over the iterations.




There is nothing wrong with declaring a variable in a for loop. 
It's just limited to the scope inside the for loop so it's not 
useful if you need the variable after the for loop ends.


Also just the declaration auto m; outside the for loop does not 
make sense either - auto needs an Right Hand Side expression.


So what is the correct way of doing it?


You can type out the return type. It can be a little tricky to 
determine sometimes though so you can also use typeof() like: 
typeof(match(greetings[i], r) m; to get the proper type.


You should use matchFirst and matchAll instead of match and the 
"g" flag. It's more clear and easier to use.


What are you trying to do in this bit of code? There may be a 
better overall structure.


Re: Regex match in for loop

2014-07-15 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jul 15, 2014 at 08:18:55PM +, seany via Digitalmars-d-learn wrote:
> Consider this:
> 
> import std.stdio, std.regex, std.array, std.algorithms ;
> 
> void main(string args[])
> {
> 
> string[] greetings = ["hello", "hallo", "hoi", "salut"];
> 
> regex r = regex("hello", "g");
> 
> for(short i = 0; i < greetings.count(); i++)
> {
> 
>   auto m = match(greetings[i], r);
> }
> 
> }
> 
> To the best of my knowledge, declaring a variable inside a for loop is
> illegal, you can not delacre the same variable repeatedly over the
> iterations.

Says who? Each instance of 'm' only exists for the duration of a single
loop iteration, so it's perfectly fine to reuse the same name the next
time round. It would be a horribly crippled language if you couldn't
declare temporary variables inside the loop body!


> Also just the declaration auto m; outside the for loop does not make
> sense either - auto needs an Right Hand Side expression.
> 
> So what is the correct way of doing it?

What you have is already (mostly) correct, except:

(1) You misspelled 'std.algorithm' as 'std.algorithms';

(2) Your declaration of 'r' should use 'auto', not 'regex':

auto r = regex("hello", "g");

Or, if you wish to be explicit, the correct type name is
'Regex!char':

Regex!char r = regex("hello", "g");

Once you fix (1) and (2), the code will work just fine.


T

-- 
Indifference will certainly be the downfall of mankind, but who cares? -- 
Miquel van Smoorenburg


Regex match in for loop

2014-07-15 Thread seany via Digitalmars-d-learn

Consider this:

import std.stdio, std.regex, std.array, std.algorithms ;

void main(string args[])
{

string[] greetings = ["hello", "hallo", "hoi", "salut"];

regex r = regex("hello", "g");

for(short i = 0; i < greetings.count(); i++)
{

  auto m = match(greetings[i], r);
}

}

To the best of my knowledge, declaring a variable inside a for 
loop is illegal, you can not delacre the same variable repeatedly 
over the iterations.


Also just the declaration auto m; outside the for loop does not 
make sense either - auto needs an Right Hand Side expression.


So what is the correct way of doing it?


Re: for loop parens

2013-07-13 Thread H. S. Teoh
On Sat, Jul 13, 2013 at 05:08:11PM +0200, JS wrote:
> On Saturday, 13 July 2013 at 01:06:09 UTC, H. S. Teoh wrote:
[...]
> >I find this fixation on syntax rather strange. As long as the syntax
> >is not *too* ugly (*cough*C++ templates*cough*) isn't the *semantics*
> >more important? A pretty language that has limited expressiveness is
> >useless; a powerful language that's a bit ugly in syntax isn't any
> >less powerful because of it.
> >
> 
> Of course, .net demonstrates this very well... but do you really
> expect most people to really be able to think that abstractly?
> Syntax is meaningless but necessary... see
> http://en.wikipedia.org/wiki/Malbolge.

That's not a fair example. I *did* say, as long as the syntax is not
*too* ugly. Malbolge doesn't qualify. :)  I mean, if you really want to
push this to the extreme, you could say we should all just write lambda
expressions, since it's all Turing-complete anyway.

The difference between D and Malbolge is on a totally different scale
than the difference between for(...){...} and for ...{...}. Just because
the difference between walking to a destination vs. driving there is a
big difference, doesn't mean that the difference between whether you
wear a red shirt vs. a white shirt while travelling is an important
issue.


T

-- 
Windows 95 was a joke, and Windows 98 was the punchline.


Re: for loop parens

2013-07-13 Thread Russel Winder
On Sat, 2013-07-13 at 12:43 +0200, ixid wrote:
> > I think that Python has syntax evidently and demonstrably 
> > superior to D. Why not Python?
> 
> White spaces with meaning cause hard to find bugs, the Python 
> syntax is not appropriate for large projects and this is well 
> known. That is not the case for the small changes Go has made.

Who says Python is not appropriate for large projects? What is their
authority for saying this?

This claim is certainly not well known, nor is it understood or believed
by anyone undertaking serious software projects that involve Python.

Some of the enforced syntactic constraints of Go due to the deduced
semi-colon insertion, are awful and ugly, in my opinion. To hide the
issues by trying to make a benefit from there being "one and only one
allowable style of Go code" enforced by gofmt is actually running away
from the real problem. 

Personally I think parentheses enclosing the control expressions in for
statements and end of statement semi-colons are anachronisms. C++ and D
choose to keep them, which is irritating. Go always has end of statement
semi-colons even if the source code appears not to.
-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder


signature.asc
Description: This is a digitally signed message part


Re: for loop parens

2013-07-13 Thread JS

On Saturday, 13 July 2013 at 01:06:09 UTC, H. S. Teoh wrote:

On Fri, Jul 12, 2013 at 05:51:21PM -0700, Brad Roberts wrote:

On 7/12/13 1:46 PM, ixid wrote:

[...]
>It seems a pity that D is achieving such power and elegance 
>in some
>areas while failing to take on some of the syntactic beauty 
>that is
>within reach. The ultimate language would look something like 
>D
>crossed with Go in my eyes. It would be interesting if 
>someone were
>able to make a D subset that showed what it could look like. 
>There is

>significant value to being easy to read and write, making the
>language naturally more appealing for users just as speed 
>makes

>applications much more attractive to users.

One person's beauty is another person's ugly.  This is an area 
that
reasonable people are going to disagree on.  You're feeling on 
their

reasons is rather dismissive.


I find this fixation on syntax rather strange. As long as the 
syntax is
not *too* ugly (*cough*C++ templates*cough*) isn't the 
*semantics* more
important? A pretty language that has limited expressiveness is 
useless;
a powerful language that's a bit ugly in syntax isn't any less 
powerful

because of it.



Of course, .net demonstrates this very well... but do you really 
expect most people to really be able to think that abstractly? 
Syntax is meaningless but necessary... see 
http://en.wikipedia.org/wiki/Malbolge.


Re: for loop parens

2013-07-13 Thread bearophile

ixid:

White spaces with meaning cause hard to find bugs, the Python 
syntax is not appropriate for large projects and this is well 
known.


Well known by who? What's your evidence? My experience says 
otherwise :-)


Bye,
bearophile


Re: for loop parens

2013-07-13 Thread ixid
I think that Python has syntax evidently and demonstrably 
superior to D. Why not Python?


White spaces with meaning cause hard to find bugs, the Python 
syntax is not appropriate for large projects and this is well 
known. That is not the case for the small changes Go has made.


Re: for loop parens

2013-07-13 Thread monarch_dodra

On Saturday, 13 July 2013 at 06:56:46 UTC, Ali Çehreli wrote:
On 07/12/2013 10:34 PM, QAston wrote:> On Saturday, 13 July 
2013 at 04:42:58 UTC, QAston wrote:

>> Also, i don't know what's wrong with parens - 2 additional
keystrokes?
>> I didn't see a for loop i a long time - ranges + foreach are
>> everywhere. And foreach is 4 chars more to type than for :P.
>
> Replying to myself, but well, this is flawed, foreach is
ususally
> shorter than for.

Especially when for loops can be infinitely long. :) I think 
the actual syntax of 'for' may be surprising to most:


  http://dlang.org/statement.html#ForStatement

import std.stdio;

void main()
{
for ( {
int i = 0;
double d = 0.5;

struct S
{
string s;
}

auto s = S("hello");

writeln("I am in the initialization clause of a for 
loop!");

} i < 10; ++i) {

writeln("i: ", i, ", d: ", d);
d /= s.s.length;
}
}

Ali


I love this feature so much ^^


Re: for loop parens

2013-07-13 Thread Ali Çehreli
On 07/12/2013 10:34 PM, QAston wrote:> On Saturday, 13 July 2013 at 
04:42:58 UTC, QAston wrote:

>> Also, i don't know what's wrong with parens - 2 additional keystrokes?
>> I didn't see a for loop i a long time - ranges + foreach are
>> everywhere. And foreach is 4 chars more to type than for :P.
>
> Replying to myself, but well, this is flawed, foreach is ususally
> shorter than for.

Especially when for loops can be infinitely long. :) I think the actual 
syntax of 'for' may be surprising to most:


  http://dlang.org/statement.html#ForStatement

import std.stdio;

void main()
{
for ( {
int i = 0;
double d = 0.5;

struct S
{
string s;
}

auto s = S("hello");

    writeln("I am in the initialization clause of a for loop!");
} i < 10; ++i) {

writeln("i: ", i, ", d: ", d);
d /= s.s.length;
}
}

Ali



Re: for loop parens

2013-07-12 Thread Jonathan M Davis
On Saturday, July 13, 2013 07:03:28 QAston wrote:
> On Saturday, 13 July 2013 at 04:56:19 UTC, Jonathan M Davis wrote:
> > On Saturday, July 13, 2013 06:42:57 QAston wrote:
> >> On Friday, 12 July 2013 at 20:46:21 UTC, ixid wrote:
> >> > Yes, I don't expect anyone to change their opinion though
> >> > frankly the anti-groups opinions feel more like attachment to
> >> > the status quo than something that's evidently and
> >> > demonstrably
> >> > superior.
> >> 
> >> I think that Python has syntax evidently and demonstrably
> >> superior to D. Why not Python?
> > 
> > I think that that's very disputable. In general, which syntax
> > is better than
> > another syntax is very subjective. Personally, I hate Python's
> > syntax and find
> > it far harder to deal with than that of languages like C/C++ or
> > D. The lack of
> > braces alone is a huge annoyance for editing code (being able
> > to hop between
> > braces in an editor is invaluable for getting to the beginning
> > and end of
> > functions, scopes, classes, etc.), and it's easy enough to find
> > rants where
> > people have had bugs in their python code due to spacing issues
> > and how it
> > cost them hours to find them.
> > 
> > Yes. Some people prefer python's syntax, but I don't see how
> > anyone could
> > possibly claim that it was demonstratably superior. It's
> > primarily a
> > subjective issue, and from what I've seen, the objective
> > portions of the
> > argument are very much against python as having braces and
> > semicolons and the
> > like makes the code more explicit and therefore less prone to
> > scoping issues.
> > So while that tradeoff may very well be worth it for some
> > people, it's
> > certainly not an objective advantage for python's syntax.
> > 
> > - Jonathan M Davis
> 
> I agree, I was just playing games with ixid.

Ah. Clearly I read through the posts too quickly.

I should probably add though that the problems that the lack of braces cause 
in python with regards to moving around in the code in an editor also apply to 
parens, which would be an objective reason why getting rid of parens on for 
loops would cause problems. Obviously, it could be argued that how the code 
looks without parens would be better than with parens and worth the problems 
it would cause with text editors, but that would be a completely subjective 
argument.

- Jonathan M Davis


Re: for loop parens

2013-07-12 Thread QAston

On Saturday, 13 July 2013 at 04:42:58 UTC, QAston wrote:
Also, i don't know what's wrong with parens - 2 additional 
keystrokes? I didn't see a for loop i a long time - ranges + 
foreach are everywhere. And foreach is 4 chars more to type 
than for :P.


Replying to myself, but well, this is flawed, foreach is ususally 
shorter than for.


Re: for loop parens

2013-07-12 Thread QAston

On Saturday, 13 July 2013 at 04:56:19 UTC, Jonathan M Davis wrote:

On Saturday, July 13, 2013 06:42:57 QAston wrote:

On Friday, 12 July 2013 at 20:46:21 UTC, ixid wrote:
> Yes, I don't expect anyone to change their opinion though
> frankly the anti-groups opinions feel more like attachment to
> the status quo than something that's evidently and 
> demonstrably

> superior.

I think that Python has syntax evidently and demonstrably
superior to D. Why not Python?


I think that that's very disputable. In general, which syntax 
is better than
another syntax is very subjective. Personally, I hate Python's 
syntax and find
it far harder to deal with than that of languages like C/C++ or 
D. The lack of
braces alone is a huge annoyance for editing code (being able 
to hop between
braces in an editor is invaluable for getting to the beginning 
and end of
functions, scopes, classes, etc.), and it's easy enough to find 
rants where
people have had bugs in their python code due to spacing issues 
and how it

cost them hours to find them.

Yes. Some people prefer python's syntax, but I don't see how 
anyone could
possibly claim that it was demonstratably superior. It's 
primarily a
subjective issue, and from what I've seen, the objective 
portions of the
argument are very much against python as having braces and 
semicolons and the
like makes the code more explicit and therefore less prone to 
scoping issues.
So while that tradeoff may very well be worth it for some 
people, it's

certainly not an objective advantage for python's syntax.

- Jonathan M Davis


I agree, I was just playing games with ixid.


Re: for loop parens

2013-07-12 Thread Jonathan M Davis
On Saturday, July 13, 2013 06:42:57 QAston wrote:
> On Friday, 12 July 2013 at 20:46:21 UTC, ixid wrote:
> > Yes, I don't expect anyone to change their opinion though
> > frankly the anti-groups opinions feel more like attachment to
> > the status quo than something that's evidently and demonstrably
> > superior.
> 
> I think that Python has syntax evidently and demonstrably
> superior to D. Why not Python?

I think that that's very disputable. In general, which syntax is better than 
another syntax is very subjective. Personally, I hate Python's syntax and find 
it far harder to deal with than that of languages like C/C++ or D. The lack of 
braces alone is a huge annoyance for editing code (being able to hop between 
braces in an editor is invaluable for getting to the beginning and end of 
functions, scopes, classes, etc.), and it's easy enough to find rants where 
people have had bugs in their python code due to spacing issues and how it 
cost them hours to find them.

Yes. Some people prefer python's syntax, but I don't see how anyone could 
possibly claim that it was demonstratably superior. It's primarily a 
subjective issue, and from what I've seen, the objective portions of the 
argument are very much against python as having braces and semicolons and the 
like makes the code more explicit and therefore less prone to scoping issues. 
So while that tradeoff may very well be worth it for some people, it's 
certainly not an objective advantage for python's syntax.

- Jonathan M Davis


Re: for loop parens

2013-07-12 Thread QAston

On Friday, 12 July 2013 at 20:46:21 UTC, ixid wrote:
Yes, I don't expect anyone to change their opinion though 
frankly the anti-groups opinions feel more like attachment to 
the status quo than something that's evidently and demonstrably 
superior.
I think that Python has syntax evidently and demonstrably 
superior to D. Why not Python?


It seems a pity that D is achieving such power and elegance in 
some areas while failing to take on some of the syntactic 
beauty that is within reach. The ultimate language would look 
something like D crossed with Go in my eyes. It would be 
interesting if someone were able to make a D subset that showed 
what it could look like. There is significant value to being 
easy to read and write, making the language naturally more 
appealing for users just as speed makes applications much more 
attractive to users.


There won't be an ultimate language - ever. People haven't 
settled up even on tabs vs spaces or braces issues yet.


Please keep in mind that every change made to the langage has 
costs that have to be paid for the benefits. Sometimes costs are 
not worth paying for the potential benefits. Status quo has this 
wonderful feature - it has 0 cost, so the benefit/cost ratio 
approaches infinity :).


Also, i don't know what's wrong with parens - 2 additional 
keystrokes? I didn't see a for loop i a long time - ranges + 
foreach are everywhere. And foreach is 4 chars more to type than 
for :P.




Re: for loop parens

2013-07-12 Thread H. S. Teoh
On Sat, Jul 13, 2013 at 03:19:04AM +0200, ixid wrote:
> >As long as the syntax is not *too* ugly (*cough*C++ templates*cough*)
> >isn't the *semantics* more important? A pretty language that has
> >limited expressiveness is useless; a powerful language that's a bit
> >ugly in syntax isn't any less powerful because of it.
[...]
> What is the cost of expressiveness in these cases?

But that's the issue, this is just a cosmetic change that doesn't really
add expressiveness to the language.


> I don't think expressiveness should be limited and often prettiness
> lends itself to expressiveness. People find D templates much easier to
> use than C++ ones and in part that's because they're much easier for
> humans to parse.

But I find C's for-loop syntax easier to parse, because what's in the
preamble is clearly distinguished from what's in the loop body. Omitting
the parens would make it visually more similar to the loop body, and
thus more liable to be confused with it.

I think comparing this to D vs. C++ template syntax is a bit unfair. C++
templates made a bad choice of using angle brackets, which are already
being used for comparison operators, thus things like func(x)>y are
ambiguous: is it func<(a(x) > y, or is it func<(a(x))> y? Not to
mention func> is actually syntactically invalid until C++11 (how
many years did it take for them to fix that one!). D templates are so
much better, in part because they use normal parentheses, which *don't*
suffer from ambiguity with existing operators.

In the case of optional parens in for-loops, there are no such ambiguity
issues involved. It's more a matter of personal preference than anything
else, IMO.


T

-- 
To err is human; to forgive is not our policy. -- Samuel Adler


Re: for loop parens

2013-07-12 Thread ixid

As long as the syntax is
not *too* ugly (*cough*C++ templates*cough*) isn't the 
*semantics* more
important? A pretty language that has limited expressiveness is 
useless;
a powerful language that's a bit ugly in syntax isn't any less 
powerful

because of it.


T


What is the cost of expressiveness in these cases? I don't think 
expressiveness should be limited and often prettiness lends 
itself to expressiveness. People find D templates much easier to 
use than C++ ones and in part that's because they're much easier 
for humans to parse.


Re: for loop parens

2013-07-12 Thread H. S. Teoh
On Fri, Jul 12, 2013 at 05:51:21PM -0700, Brad Roberts wrote:
> On 7/12/13 1:46 PM, ixid wrote:
[...]
> >It seems a pity that D is achieving such power and elegance in some
> >areas while failing to take on some of the syntactic beauty that is
> >within reach. The ultimate language would look something like D
> >crossed with Go in my eyes. It would be interesting if someone were
> >able to make a D subset that showed what it could look like. There is
> >significant value to being easy to read and write, making the
> >language naturally more appealing for users just as speed makes
> >applications much more attractive to users.
> 
> One person's beauty is another person's ugly.  This is an area that
> reasonable people are going to disagree on.  You're feeling on their
> reasons is rather dismissive.

I find this fixation on syntax rather strange. As long as the syntax is
not *too* ugly (*cough*C++ templates*cough*) isn't the *semantics* more
important? A pretty language that has limited expressiveness is useless;
a powerful language that's a bit ugly in syntax isn't any less powerful
because of it.


T

-- 
There are two ways to write error-free programs; only the third one works.


Re: for loop parens

2013-07-12 Thread Brad Roberts

On 7/12/13 1:46 PM, ixid wrote:

They are not issues in Go, but Walter is strongly against optional semicolons, 
as bearophile said.
Me and others (like you) like optional semicolons, but since Walter doesn't and 
it's his language,
that will not change.

I personally understand much better the code without semicolons, like in Ruby 
and Python. And
making a parser that way isn't that much difficult, and error recovery is as 
powerful.


Yes, I don't expect anyone to change their opinion though frankly the 
anti-groups opinions feel more
like attachment to the status quo than something that's evidently and 
demonstrably superior.

It seems a pity that D is achieving such power and elegance in some areas while 
failing to take on
some of the syntactic beauty that is within reach. The ultimate language would 
look something like D
crossed with Go in my eyes. It would be interesting if someone were able to 
make a D subset that
showed what it could look like. There is significant value to being easy to 
read and write, making
the language naturally more appealing for users just as speed makes 
applications much more
attractive to users.


One person's beauty is another person's ugly.  This is an area that reasonable people are going to 
disagree on.  You're feeling on their reasons is rather dismissive.


Re: for loop parens

2013-07-12 Thread ixid
I'm not sure how much of a problem it is, especially given that 
Go has a
strict style guide, but the objection has come up that these 
two are

very different:

  if i < f() {
  g()
  }

and

  if i < f()
  {
  g()
  }

In the second case, a semicolon is inserted on the same line as 
the if.


However, like I said, in idiomatic Go, this is simply not a 
done thing.


Why would:

if i < f()

gain a semi-colon? I thought the Go rules require that a line 
would compile to add the semi-colon. In D at least wouldn't the 
line have to be:


if i < f() {}

before the compiler would add a semi-colon to it?


Re: for loop parens

2013-07-12 Thread ixid
They are not issues in Go, but Walter is strongly against 
optional semicolons, as bearophile said. Me and others (like 
you) like optional semicolons, but since Walter doesn't and 
it's his language, that will not change.


I personally understand much better the code without 
semicolons, like in Ruby and Python. And making a parser that 
way isn't that much difficult, and error recovery is as 
powerful.


Yes, I don't expect anyone to change their opinion though frankly 
the anti-groups opinions feel more like attachment to the status 
quo than something that's evidently and demonstrably superior.


It seems a pity that D is achieving such power and elegance in 
some areas while failing to take on some of the syntactic beauty 
that is within reach. The ultimate language would look something 
like D crossed with Go in my eyes. It would be interesting if 
someone were able to make a D subset that showed what it could 
look like. There is significant value to being easy to read and 
write, making the language naturally more appealing for users 
just as speed makes applications much more attractive to users.




Re: for loop parens

2013-07-12 Thread Simen Kjaeraas

On 2013-07-12, 22:38, ixid wrote:


On Friday, 12 July 2013 at 20:30:59 UTC, bearophile wrote:

ixid:

Similarly what are D user's potential issues with Go-like semi-colon  
rules? And would this be possible as a subset of current D code?


Such changes will not happen even in D4. Walter is strongly against the  
idea of optional semicolons, on the base that semicolons help the  
parser, so they allow better error recovery and error messages.


Bye,
bearophile


Is there any evidence that these are issues in Go?


I'm not sure how much of a problem it is, especially given that Go has a
strict style guide, but the objection has come up that these two are
very different:

  if i < f() {
  g()
  }

and

  if i < f()
  {
  g()
  }

In the second case, a semicolon is inserted on the same line as the if.

However, like I said, in idiomatic Go, this is simply not a done thing.

--
Simen


Re: for loop parens

2013-07-12 Thread bearophile

ixid:

Similarly what are D user's potential issues with Go-like 
semi-colon rules? And would this be possible as a subset of 
current D code?


Such changes will not happen even in D4. Walter is strongly 
against the idea of optional semicolons, on the base that 
semicolons help the parser, so they allow better error recovery 
and error messages.


Bye,
bearophile


Re: for loop parens

2013-07-12 Thread Ary Borenszweig

On 7/12/13 5:38 PM, ixid wrote:

On Friday, 12 July 2013 at 20:30:59 UTC, bearophile wrote:

ixid:


Similarly what are D user's potential issues with Go-like semi-colon
rules? And would this be possible as a subset of current D code?


Such changes will not happen even in D4. Walter is strongly against
the idea of optional semicolons, on the base that semicolons help the
parser, so they allow better error recovery and error messages.

Bye,
bearophile


Is there any evidence that these are issues in Go? That sounds like a
theoretical objection that isn't attackable when no one has done it but
turns out not to be terribly important when someone actually does it.


They are not issues in Go, but Walter is strongly against optional 
semicolons, as bearophile said. Me and others (like you) like optional 
semicolons, but since Walter doesn't and it's his language, that will 
not change.


I personally understand much better the code without semicolons, like in 
Ruby and Python. And making a parser that way isn't that much difficult, 
and error recovery is as powerful.


Re: for loop parens

2013-07-12 Thread ixid

On Friday, 12 July 2013 at 20:30:59 UTC, bearophile wrote:

ixid:

Similarly what are D user's potential issues with Go-like 
semi-colon rules? And would this be possible as a subset of 
current D code?


Such changes will not happen even in D4. Walter is strongly 
against the idea of optional semicolons, on the base that 
semicolons help the parser, so they allow better error recovery 
and error messages.


Bye,
bearophile


Is there any evidence that these are issues in Go? That sounds 
like a theoretical objection that isn't attackable when no one 
has done it but turns out not to be terribly important when 
someone actually does it.


Re: for loop parens

2013-07-12 Thread ixid

On Friday, 12 July 2013 at 20:02:46 UTC, bearophile wrote:

ixid:


If curly brackets were required where parens were omitted
what would prevent such a syntax in D?


Maybe nothing, beside lot of programmers that want the 
"freedom" to omit curly brackets :-)


Bye,
bearophile


Similarly what are D user's potential issues with Go-like 
semi-colon rules? And would this be possible as a subset of 
current D code?




Re: for loop parens

2013-07-12 Thread bearophile

ixid:


If curly brackets were required where parens were omitted
what would prevent such a syntax in D?


Maybe nothing, beside lot of programmers that want the "freedom" 
to omit curly brackets :-)


Bye,
bearophile


Re: for loop parens

2013-07-12 Thread ixid

On Friday, 12 July 2013 at 19:44:43 UTC, bearophile wrote:

ixid:

Go and Rust seem to have been able to dispense with the parens 
in for loops, is this something that would be possible to do 
in D or are there parsing and grammatical reasons not to do 
this?


Go has chosen a different syntax. I don't think D syntax of for 
loops can change now...


Bye,
bearophile


Humour me. =) Perhaps as a discussion over a D3 language. If 
curly brackets were required where parens were omitted what would 
prevent such a syntax in D?


Re: for loop parens

2013-07-12 Thread bearophile

ixid:

Go and Rust seem to have been able to dispense with the parens 
in for loops, is this something that would be possible to do in 
D or are there parsing and grammatical reasons not to do this?


Go has chosen a different syntax. I don't think D syntax of for 
loops can change now...


Bye,
bearophile


for loop parens

2013-07-12 Thread ixid
Go and Rust seem to have been able to dispense with the parens in 
for loops, is this something that would be possible to do in D or 
are there parsing and grammatical reasons not to do this?


Re: Why do i have to add to the counter when using for loop to perfectly get result?

2013-05-30 Thread estew
Well, after a quick glance at the code you're iterating N times 
but only printing N-1 times. When counter == peak the loop does 
nothing so you'd get something like:


chosen=5
for(int counter = 0; counter < chosen ; ++counter){ // note +1 
removed }


counter = 0, 1, 2, [3]NO_PRINT, 4
  *0
 ***1
*2
 ***4

(note: my ascii art, I assume this is what the code would 
produce...)

Now add the +1
for(int counter = 0; counter < chosen +1 ; ++counter){
0, 1, 2, [3]skip, 4, 5
  *0
 ***1
*2
 ***4
  *5

With your implementation as it stands you need to skip iteration 
N/2+1 to get the correct output. But you still need to write N 
lines.


Hope that makes sense...!! :D
Stewart


Why do i have to add to the counter when using for loop to perfectly get result?

2013-05-30 Thread Tori
/* licenced under the wtfpl license :D... as if i even understand 
how to license*/





import std.stdio;

void main(){
//yeah... im making a diamond pattern out off asterisks
writeln("Pick a number that is odd");
int chosen;
bool oddnoteven = false;
while(oddnoteven == false){
write("Enter number here: ");
readf(" %s", &chosen);
int numbercheck = chosen % 2;
if(numbercheck == 0){
			writeln("I really don't like even numbers mofo >:/... Just odd 
ones.. Try again? :D");

}
else{
oddnoteven = true;
}
}

int peak = (chosen + 1)/2;


	for(int counter = 0; counter < chosen + 1; ++counter){ // my fro 
block

//Ok its not broken DO NOT KILL THE BLOCK!
if(counter < peak){
int spacesneeded = (peak - counter) - 1;
			for(int spacesmade = 0 ; spacesmade < spacesneeded; 
++spacesmade ){

write(" ");
}
			int shotsneeded = (2*counter) + 1;//(countxXXXerx + 1) +x 
(counterx + 1)/x2; uhh nope

for(int shotsmade = 0; shotsmade < shotsneeded; 
++shotsmade){
write("*");
}
writeln();
}
//hmmm bastard block... >:/
if(counter > peak){
int spacesneeded = (counter - peak);
			for(int spacesmade = 0; spacesmade < spacesneeded; 
++spacesmade){

write(" ");
}
int shotsneeded = (2*(chosen - counter))+ 1;
			for(int shotsfired = 0; shotsfired < shotsneeded; 
++shotsfired){

write("*");
}
writeln();
}
}
}


ok i know its bad math, hope its not too much of a waste of serv 
space. so can someone shoot me an explain about why in my "fro 
block" i hav to add "+1" to chosen to perfectly make the diamond 
shape.. but it i take out the " + 1" it cuts of the last print... 
help please :(


Re: a FOR loop and floating variables

2013-05-02 Thread bearophile

Simen Kjaeraas:

Both 5 and 9 in the second example are integers (int). When you 
divide

one int by another, the result is an int, and hence (5/9) is 0.


Yes, smarter languages (like Pascal..., but also Python, Ada, 
etc) have two different division operators to avoid such silly C 
semantics, that sometimes causes bugs.


Bye,
bearophile


Re: a FOR loop and floating variables

2013-05-02 Thread Martin Drašar

Dne 2.5.2013 20:14, Carlos napsal(a):

I have this code :

import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5.0/9.0)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}
  Which works. but if I change the "5.0" for "5" I get cero on the
celsius side.

import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5/9)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}

So why is this ?


Hi Carlos,

the second code performs integral division which very much behave like 
floating-point division, but the fractional part is chopped off.


 5/9 ~ 0.556 => 0
10/9 ~ 1.111 => 1

If you want precise (i.e. floating point) results, you have to have at 
least one float or double in your equation.


This would work:

write(fahr, "\t", (5.0/9)*(fahr-32), "\n");

Regards,
Martin


Re: a FOR loop and floating variables

2013-05-02 Thread Simen Kjaeraas

On 2013-05-02, 20:14, Carlos wrote:


I have this code :

import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5.0/9.0)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}
  Which works. but if I change the "5.0" for "5" I get cero on the  
celsius side.


import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5/9)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}

So why is this ?


Both 5 and 9 in the second example are integers (int). When you divide
one int by another, the result is an int, and hence (5/9) is 0.

--
Simen


a FOR loop and floating variables

2013-05-02 Thread Carlos

I have this code :

import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5.0/9.0)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}
 Which works. but if I change the "5.0" for "5" I get cero on the 
celsius side.


import std.stdio;
import std.c.stdlib;
void main()
{
int fahr;
write("F\tC\n");
for (fahr = 0; fahr <= 300; fahr = fahr + 20)
write(fahr, "\t", (5/9)*(fahr-32), "\n");
write("Done!\n");
exit (0);
}

So why is this ?


Re: for loop

2012-01-23 Thread Jonathan M Davis
On Monday, January 23, 2012 19:48:02 Timon Gehr wrote:
> On 01/23/2012 07:06 PM, bearophile wrote:
> > Ellery Newcomer:
> >> void main(){
> >> 
> >> for ({int x=0; short y=0;} x< 10; x++, y++){
> >> }
> >> 
> >> }
> > 
> > I don't understand, is that a compiler bug?
> > Aren't x and y in a sub-scope that ends before you use x and y?
> > 
> > Bye,
> > bearophile
> 
> It is not a bug.
> 
> ForStatement:
> for (Initialize Testopt ; Incrementopt) ScopeStatement
> Initialize:
> ;
> NoScopeNonEmptyStatement
> 
> Initialize is NoScope.

That's a pretty cool feature actually, since it gives you much more flexibility 
with regards to the types of the variables that you declare in the beginning 
of the for loop (or other things that you might want to do to the variables 
prior to running the loop. My only concern with it would be programmers not 
understanding it, because they're not used to it. I may start using.

- Jonathan M Davis


Re: for loop

2012-01-23 Thread Timon Gehr

On 01/23/2012 07:06 PM, bearophile wrote:

Ellery Newcomer:


void main(){
  for ({int x=0; short y=0;} x<  10; x++, y++){
  }
}


I don't understand, is that a compiler bug?
Aren't x and y in a sub-scope that ends before you use x and y?

Bye,
bearophile


It is not a bug.

ForStatement:
for (Initialize Testopt ; Incrementopt) ScopeStatement
Initialize:
;
NoScopeNonEmptyStatement

Initialize is NoScope.


Re: for loop

2012-01-23 Thread Mantis

23.01.2012 20:06, bearophile пишет:

Ellery Newcomer:


void main(){
  for ({int x=0; short y=0;} x<  10; x++, y++){
  }
}

I don't understand, is that a compiler bug?
Aren't x and y in a sub-scope that ends before you use x and y?

Bye,
bearophile

According to specs, this is BlockStatement that doesn't create scope, if 
I don't miss anything.


Re: for loop

2012-01-23 Thread bearophile
Ellery Newcomer:

> void main(){
>  for ({int x=0; short y=0;} x < 10; x++, y++){
>  }
> }

I don't understand, is that a compiler bug?
Aren't x and y in a sub-scope that ends before you use x and y?

Bye,
bearophile


Re: for loop

2012-01-23 Thread Trass3r

void main(){
   for ({int x=0; short y=0;} x < 10; x++, y++){
   }
}


wtf?


Re: for loop

2012-01-23 Thread Ellery Newcomer

On 01/22/2012 11:37 AM, Zachary Lund wrote:


This is an ugly solution (and I'm not 100% sure it's valid D) but:

/+/
void main() {
{
short y = 0;
int x = 0;

for (; x < 10; ++x, ++y)
{
}
}
}
/+/


raise you.


void main(){
for ({int x=0; short y=0;} x < 10; x++, y++){
}
}


Re: for loop

2012-01-22 Thread Zachary Lund

On 01/22/2012 11:37 AM, Zachary Lund wrote:

On 01/22/2012 11:08 AM, bearophile wrote:

Max Klyga:


If you want to declare and initialize several variables in the for
loop, you can do it if they are of the same type:

for (int x = 0, y = 0; ...; .++x, ++y) { ... }


And if you need different types this sometimes is enough:

void main() {
for (auto x = 0, y = 0.0; x< 10; x++, y++) {
}
}

Bye,
bearophile


This is an ugly solution (and I'm not 100% sure it's valid D) but:

/+/
void main() {
{
short y = 0;
int x = 0;

for (; x < 10; ++x, ++y)
{
}
}
}
/+/


LOL, well... I missed the post that said the exact same thing I did. Oh 
well...


Re: for loop

2012-01-22 Thread Zachary Lund

On 01/22/2012 11:08 AM, bearophile wrote:

Max Klyga:


If you want to declare and initialize several variables in the for
loop, you can do it if they are of the same type:

for (int x = 0, y = 0; ...; .++x, ++y) { ... }


And if you need different types this sometimes is enough:

void main() {
 for (auto x = 0, y = 0.0; x<  10; x++, y++) {
 }
}

Bye,
bearophile


This is an ugly solution (and I'm not 100% sure it's valid D) but:

/+/
void main() {
{
short y = 0;
int x = 0;

for (; x < 10; ++x, ++y)
{
}
}
}
/+/


Re: for loop

2012-01-22 Thread bearophile
Max Klyga:

> If you want to declare and initialize several variables in the for 
> loop, you can do it if they are of the same type:
> 
> for (int x = 0, y = 0; ...; .++x, ++y) { ... }

And if you need different types this sometimes is enough:

void main() {
for (auto x = 0, y = 0.0; x < 10; x++, y++) {
}
}

Bye,
bearophile


Re: for loop

2012-01-22 Thread Max Klyga

On 2012-01-22 16:23:36 +0300, RenatoL said:


This works:

import std.stdio;
void main()
{
int x = 0;
int y = 0;
for(; ((x < 5) && (y < 5)); x++, y ++)
{
writeln("x + y = ", x + y);
}
}

The question is easy: is it possible to insert x and y internally
in the for header? that is something like C#

for (int x = 0, int y = 0; .)

this doesn't work in D.


If you want to declare and initialize several variables in the for 
loop, you can do it if they are of the same type:


for (int x = 0, y = 0; ...; .++x, ++y) { ... }



Re: for loop

2012-01-22 Thread RenatoL
Ops, tk u .. sometimes C# is a bad teacher :-)


Re: for loop

2012-01-22 Thread Trass3r

for (int x = 0, int y = 0; .)


for (int x=0, y=0; ...)


for loop

2012-01-22 Thread RenatoL
This works:

import�std.stdio;
void�main()
{
int�x =�0;
int�y =�0;
for(;�((x�<�5)�&&�(y�<�5));�x++,�y�++)
{
writeln("x + y = ",�x�+�y);
}
}

The question is easy: is it possible to insert x and y internally
in the for header? that is something like C#

for (int x = 0, int y = 0; .)

this doesn't work in D.