Re: Storing struct in a array

2018-01-09 Thread Vino via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 17:41:10 UTC, Vino wrote:

On Tuesday, 9 January 2018 at 17:00:05 UTC, thedeemon wrote:

On Tuesday, 9 January 2018 at 13:49:41 UTC, Vino wrote:

Hi All,

 It is possible to store struct in a array ans use the same 
in csvReader


Sure, you can just pass the type of your struct to csvReader:

struct Layout { string name; int value; double other; }

auto readArrayOfStructs(string fname) {
Array!Layout res;
foreach(record; fname.readText.csvReader!Layout('\t')) {
res ~= record;
}
return res;
}


Hi Deemon,

  Thank you, and sorry for the confusion, the requirement is as 
below


auto reader(T) (Array!T T1s, T fname) {
auto uFile = File(fName, "r");
foreach (record; 
uFile.byLineCopy().joiner("\n").csvReader!(Tuple!T1s)) // 
receive the type and fetch the record

writeln(record);
}

void main () {
auto fName = 
"C:\\Users\\bheev1\\Desktop\\Current\\Script\\Others\\Table1.csv";

struct T1 { string Name; string Country; int Age; }
Array!T1 T1s;
reader(fName, T1s); // pass the array Type as a function 
parameter

}


From,
Vino.B


Details

For example let say we have 3 struct
auto read(T) (T Filename, T ArrayType) {
T ArrayType res;
foreach (record; 
Filename.byLineCopy().joiner("\n").csvReader!(T)(Tuple!ArrayType))

foreach(i, T; ColumnTypes) { res[i].insert(record[i]); }
}
return res;
}

void main () {

struct S1 { }
struct S2 { }
struct S3 { }

Get user input(UI)
if(UI == S1) {
Array!S1 T1;
writeln(read(File1, Array Type));
}

From,
Vino.B




Re: Is old style compile-time foreach redundant?

2018-01-09 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/9/18 2:31 PM, H. S. Teoh wrote:

On Tue, Jan 09, 2018 at 02:24:11PM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:
[...]

A break or continue is simply a goto underneath. A goto in an unrolled
loop isn't much different than a goto in a um... rolled loop :) It's
just that there are copies of each loop body, and the gotos need
copies of the labels.

So no, it's not "interpreted" by the foreach statement, but the
foreach statement provides the anchors for the goto label targets.


True.


[...]

And then of course, the optimizer weeds out the unreachable
statements.  Doing this with static foreach wouldn't be as pleasant.
You'd have to branch the entire loop body, or use a goto in the case
of a break.

[...]

If there were a hypothetical `static continue` or `static break` that's
recognized by the static foreach unroller, we could in theory automate
this branching in the compiler itself, e.g., by deleting the AST nodes
that would be skipped.  Of course, the syntax need not be `static
continue`; if there were a way to overload `break LABEL;` for the same
purpose, i.e., have the static foreach unroller inspect the label to see
if it is referring to the static foreach itself, then this would work.

But I don't know the static foreach implementation enough to be able to
tell whether this is actually possible at the time static foreach is
processed, or whether there may be some chicken-and-egg problem with
inspecting the target of a break/continue before semantic or whatever.


Yeah, I think in terms of static foreach, it's not a straightforward 
problem. Because the compiler may not know enough information at the 
time to figure out whether it should still keep generating code.


For example:

static foreach(i; 0 .. 5)
{
   if(i == 3) static break;
   static assert(i < 3);
}

How does it know whether the static break should be "executed" at 
compile-time if it hasn't evaluated the if-statement? The code would 
have to have no runtime branches to make sure that static break can be 
evaluated at compile-time.


And this still puts it at a disadvantage when compared to tuple-foreach, 
at least as far as break/continue are concerned.


-Steve


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jan 09, 2018 at 02:24:11PM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:
[...]
> A break or continue is simply a goto underneath. A goto in an unrolled
> loop isn't much different than a goto in a um... rolled loop :) It's
> just that there are copies of each loop body, and the gotos need
> copies of the labels.
> 
> So no, it's not "interpreted" by the foreach statement, but the
> foreach statement provides the anchors for the goto label targets.

True.


[...]
> And then of course, the optimizer weeds out the unreachable
> statements.  Doing this with static foreach wouldn't be as pleasant.
> You'd have to branch the entire loop body, or use a goto in the case
> of a break.
[...]

If there were a hypothetical `static continue` or `static break` that's
recognized by the static foreach unroller, we could in theory automate
this branching in the compiler itself, e.g., by deleting the AST nodes
that would be skipped.  Of course, the syntax need not be `static
continue`; if there were a way to overload `break LABEL;` for the same
purpose, i.e., have the static foreach unroller inspect the label to see
if it is referring to the static foreach itself, then this would work.

But I don't know the static foreach implementation enough to be able to
tell whether this is actually possible at the time static foreach is
processed, or whether there may be some chicken-and-egg problem with
inspecting the target of a break/continue before semantic or whatever.


T

-- 
Государство делает вид, что платит нам зарплату, а мы делаем вид, что работаем.


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/9/18 11:35 AM, H. S. Teoh wrote:

On Tue, Jan 09, 2018 at 10:57:03AM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:

I may have been misleading when I made my first comment. What I mean
is that you *can't* break or continue a static foreach, even with
labels. However, you *can* do it to a standard foreach over a tuple.
This may be one reason you want to use a tuple-foreach over a static
foreach.

[...]

Actually, that's wrong too. Tuple-foreach does not interpret
break/continue either. Here's a proof:

alias Seq(A...) = A;
foreach (i; Seq!(0, 1, 2, 3)) {
static if (i==2)
break;
static assert(i < 3); // will fail on the 4th iteration
}

What actually happens is that all iterations are unrolled, then the
unreachable iterations are elided by the optimizer during codegen. The
foreach itself is not affected by break/continue at all.


A break or continue is simply a goto underneath. A goto in an unrolled 
loop isn't much different than a goto in a um... rolled loop :) It's 
just that there are copies of each loop body, and the gotos need copies 
of the labels.


So no, it's not "interpreted" by the foreach statement, but the foreach 
statement provides the anchors for the goto label targets.


e.g.:

int x;

foreach(i; Seq!(0, 1, 2, 3)) {
   x += i;
   static if(i % 2) continue;
   x *= i;
}

=>

int x;
{
   x += 0;
   x *= 0;
}
{
   x += 1;
   goto label1;
   x *= 1;
}
{
label1:
   x += 2;
   x *= 2;
}
{
   x += 3;
   goto label2;
   x *= 3;
}
label2:

And then of course, the optimizer weeds out the unreachable statements. 
Doing this with static foreach wouldn't be as pleasant. You'd have to 
branch the entire loop body, or use a goto in the case of a break.


-Steve


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jan 09, 2018 at 10:57:03AM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:
> On 1/8/18 9:27 AM, H. S. Teoh wrote:
> > On Sun, Jan 07, 2018 at 10:39:19PM -0500, Steven Schveighoffer via 
> > Digitalmars-d-learn wrote:
> > > On 1/6/18 6:25 PM, Ali Çehreli wrote:
> > > > Is 'static foreach' sufficient for all needs or is there any
> > > > value for regular foreach over compile-time sequences?
> > > 
> > > If you use continues or breaks, then you need to switch to gotos
> > > if using static foreach, as it does not support them directly.
> > [...]
> > 
> > Are you sure?  I was under te impression that it does support
> > continues and breaks -- but only if they are labelled, because of a
> > syntactic ambiguity otherwise.
> 
> I thought it only worked for constructs outside the static foreach
> (like switch).
> 
> testing...
> 
> Nope, doesn't work.

Grrr... I thought it did, but you're right, attempting to break the
static foreach with a label gets this compile error:

-
test.d(7): Error: enclosing label FE for break not found
-


> The ambiguity is that if you have a breakable or continuable construct
> outside a static foreach (e.g. switch), then you may believe that the
> break statement is affecting the foreach (in fact, that is how
> tuple-foreach works), but you are actually affecting the outer
> construct.

Yes, that's the ambiguity I was referring to. :-)


> The extra requirement is to help you realize the implication. It may
> be removed in the future.

I vaguely remember Timon mentioning something about implementing static
break / static continue, and somehow I thought the labelled break /
labelled continue was supposed to be it. Or at least, they are stand-ins
until static break/continue are implemented.  Is that no longer on the
table?


> I may have been misleading when I made my first comment. What I mean
> is that you *can't* break or continue a static foreach, even with
> labels. However, you *can* do it to a standard foreach over a tuple.
> This may be one reason you want to use a tuple-foreach over a static
> foreach.
[...]

Actually, that's wrong too. Tuple-foreach does not interpret
break/continue either. Here's a proof:

alias Seq(A...) = A;
foreach (i; Seq!(0, 1, 2, 3)) {
static if (i==2)
break;
static assert(i < 3); // will fail on the 4th iteration
}

What actually happens is that all iterations are unrolled, then the
unreachable iterations are elided by the optimizer during codegen. The
foreach itself is not affected by break/continue at all.


T

-- 
Дерево держится корнями, а человек - друзьями.


Re: Storing struct in a array

2018-01-09 Thread Vino via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 17:00:05 UTC, thedeemon wrote:

On Tuesday, 9 January 2018 at 13:49:41 UTC, Vino wrote:

Hi All,

 It is possible to store struct in a array ans use the same in 
csvReader


Sure, you can just pass the type of your struct to csvReader:

struct Layout { string name; int value; double other; }

auto readArrayOfStructs(string fname) {
Array!Layout res;
foreach(record; fname.readText.csvReader!Layout('\t')) {
res ~= record;
}
return res;
}


Hi Deemon,

  Thank you, and sorry for the confusion, the requirement is as 
below


auto reader(T) (Array!T T1s, T fname) {
auto uFile = File(fName, "r");
foreach (record; 
uFile.byLineCopy().joiner("\n").csvReader!(Tuple!T1s)) // receive 
the type and fetch the record

writeln(record);
}

void main () {
auto fName = 
"C:\\Users\\bheev1\\Desktop\\Current\\Script\\Others\\Table1.csv";

struct T1 { string Name; string Country; int Age; }
Array!T1 T1s;
reader(fName, T1s); // pass the array Type as a function parameter
}


From,
Vino.B



Re: Storing struct in a array

2018-01-09 Thread thedeemon via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 13:49:41 UTC, Vino wrote:

Hi All,

 It is possible to store struct in a array ans use the same in 
csvReader


Sure, you can just pass the type of your struct to csvReader:

struct Layout { string name; int value; double other; }

auto readArrayOfStructs(string fname) {
Array!Layout res;
foreach(record; fname.readText.csvReader!Layout('\t')) {
res ~= record;
}
return res;
}


Re: Storing struct in a array

2018-01-09 Thread thedeemon via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 18:09:58 UTC, Vino wrote:
 It is possible to store struct in a array ans use the same 
in csvReader


Sure, you can just pass the type of your struct to csvReader:



Array!T1 T1s;
reader(fName, T1s); // pass the array Type as a function 
parameter


First you write a template function that takes an array of some 
generic type and fills it with records from CSV file:


void readData(DataType)(string fname, ref Array!DataType arr) {
foreach (record; fname.readText.csvReader!DataType('\t')) {
arr ~= record;
}
}

Then you can use it in your main program with different types:

struct S1 { string name; string value; int other; }
struct S2 { int a; string b; }

void main () {
...
if (someCondition) {
Array!S1 arr1;
readData("data1.csv", arr1);
} else {
Array!S2 arr2;
readData("data2.csv", arr2);
}
}

A little advice. Kindly pause and spend an evening reading this 
book:

http://ddili.org/ders/d.en/

Currently your code pieces look like a soup produced by someone 
who still confuses variables and types, and lacks basic 
programming skills. Read the book, don't rush with writing broken 
code.


Re: Creating Struct for an output of a program.

2018-01-09 Thread Vino via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 12:50:04 UTC, Mengu wrote:

On Tuesday, 9 January 2018 at 07:57:19 UTC, Vino wrote:

[...]


if S2 consists of data for Layout struct, then you can simply 
do:


auto S2 = S1.map!(a => Layout(a[0], a[1], a[2]));

which will give you a range of Layout.


Hi,

 We want the Layout struct to be created from the output of S1, 
in the above the Layout is a example of the struct structure that 
we needed.


From,
Vino.B


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jan 09, 2018 at 03:26:32PM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:
> On 1/9/18 2:31 PM, H. S. Teoh wrote:
[...]
> > If there were a hypothetical `static continue` or `static break`
> > that's recognized by the static foreach unroller, we could in theory
> > automate this branching in the compiler itself, e.g., by deleting
> > the AST nodes that would be skipped.  Of course, the syntax need not
> > be `static continue`; if there were a way to overload `break LABEL;`
> > for the same purpose, i.e., have the static foreach unroller inspect
> > the label to see if it is referring to the static foreach itself,
> > then this would work.
> > 
> > But I don't know the static foreach implementation enough to be able
> > to tell whether this is actually possible at the time static foreach
> > is processed, or whether there may be some chicken-and-egg problem
> > with inspecting the target of a break/continue before semantic or
> > whatever.
> 
> Yeah, I think in terms of static foreach, it's not a straightforward
> problem. Because the compiler may not know enough information at the
> time to figure out whether it should still keep generating code.
> 
> For example:
> 
> static foreach(i; 0 .. 5)
> {
>if(i == 3) static break;
>static assert(i < 3);
> }
> 
> How does it know whether the static break should be "executed" at
> compile-time if it hasn't evaluated the if-statement? The code would
> have to have no runtime branches to make sure that static break can be
> evaluated at compile-time.
[...]

Static foreach does not (and should not!) evaluate a runtime branch,
because this is before CTFE even happens. CTFE cannot happen until the
static foreach has been fully unrolled, so it doesn't even make sense to
talk about evaluating the if-statement at this point. For your example
to make sense, you'd have to use static if, then the break would be
possible, and non-problematic.

Of course, that still doesn't solve the problem of what static break is
supposed to do from inside a runtime branch. I'm tempted to say that
static break should mean "delete all subsequent nodes from the AST that
follows this node in depth-first traversal order", so your example above
would be transformed into:

if (0 == 3) {}
// all subsequent iterations deleted

because the static break is unconditionally compiled (it has nothing to
do with the runtime branch).  You'd have to use static if to make it
conditionally-compiled and thus not instantly aborting the loop.

Such semantics would be logically consistent, but unfortunately rather
counterintuitive at first glance.


T

-- 
If the comments and the code disagree, it's likely that *both* are wrong. -- 
Christopher


Is there a way to get this associative array initialization to work?

2018-01-09 Thread WhatMeWorry via Digitalmars-d-learn

enum SoundType { MUSIC = 0, SOUND_EFFECT };

struct Sound
{
string file;
SoundType  musicOrSfx;
void*  ptr;   // Mix_Chunk* for sfx;  Mix_Music* for 
music;

}

immutable Sound[string] soundLibrary  =   // line 148
[
"SCRATCH"  : { file : "scratch.wav", musicOrSfx : 
SOUND_EFFECT, ptr : null },
"BACKGROUND_TRACK" : { file : "beat.wav",musicOrSfx : 
MUSIC,ptr : null },
"HIGH" : { file : "high.wav",musicOrSfx : 
SOUND_EFFECT, ptr : null }	

];  


I keep getting a
source\app.d(148,1): Error: not an associative array initializer




Re: Is old style compile-time foreach redundant?

2018-01-09 Thread H. S. Teoh via Digitalmars-d-learn
On Wed, Jan 10, 2018 at 12:18:46AM +0100, Timon Gehr via Digitalmars-d-learn 
wrote:
> On 09.01.2018 22:04, H. S. Teoh wrote:
> > if (0 == 3) {}
> > // all subsequent iterations deleted
> > 
> > because the static break is unconditionally compiled (it has nothing
> > to do with the runtime branch).  You'd have to use static if to make
> > it conditionally-compiled and thus not instantly aborting the loop.
> > 
> > Such semantics would be logically consistent, but unfortunately
> > rather counterintuitive at first glance.
> 
> I think "if (0 == 3) { static break; }" should be a compile-time error.

That's also a possible solution, perhaps a better solution than what I
described.  Make it so that static break/continue cannot be nested
inside runtime conditionals.  That should exclude all of the
pathological cases, hopefully.


T

-- 
The diminished 7th chord is the most flexible and fear-instilling chord. Use it 
often, use it unsparingly, to subdue your listeners into submission!


Re: Is there a way to get this associative array initialization to work?

2018-01-09 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 23:05:21 UTC, WhatMeWorry wrote:

source\app.d(148,1): Error: not an associative array initializer


The C-style struct initialization in there is a problem. Try 
making it


immutable Sound[string] soundLibrary  =   // line 148
[
"SCRATCH"  : Sound("scratch.wav", 
SoundType.SOUND_EFFECT, null ),
"BACKGROUND_TRACK" : Sound("beat.wav",SoundType.MUSIC,
null ),
"HIGH" : Sound("high.wav",
SoundType.SOUND_EFFECT, null

)
];

using positional values instead of named. Moreover, note that 
such initialization needs to be done in a function, not at global 
scope. you may need to declare it outside then initialize it in a 
static constructor.


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread Timon Gehr via Digitalmars-d-learn

On 09.01.2018 22:04, H. S. Teoh wrote:

if (0 == 3) {}
// all subsequent iterations deleted

because the static break is unconditionally compiled (it has nothing to
do with the runtime branch).  You'd have to use static if to make it
conditionally-compiled and thus not instantly aborting the loop.

Such semantics would be logically consistent, but unfortunately rather
counterintuitive at first glance.


I think "if (0 == 3) { static break; }" should be a compile-time error.


Re: Rvalue references

2018-01-09 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/8/18 6:07 PM, Jiyan wrote:


Sry i know i asked it already in IRC:
Are rvalue references already solved with auto ref?

https://p0nce.github.io/d-idioms/#Rvalue-references:-Understanding-auto-ref-and-then-not-using-it 



Says rvalues are moved!


But an rvalue move is cheaper. You construct it right on the stack where 
it needs to be, and no actual copy is happening. Then inside the 
function, no further indirections are needed, just stack offsets.



The other solution seems not so practical.


The other solution exploits a hole in the "rvalues cannot be references" 
mantra. Because all member functions take 'this' by reference, the 
function call can be used to blur the line between rvalues and lvalues.


It makes for some... interesting things:

struct Int
{
   int value;
   Int opBinary(string op : "+")(ref const Int other) const
   {
   return Int(other.value + value);
   }
}

auto v = Int(5);

auto v2 = s + Int(5); // error
auto v3 = Int(5) + s; // OK!

Is any solution to them intended, or was all the talk about rvalue 
references simply discarded?


auto ref was actually proposed as a non-template solution, but Walter 
implemented it the way it is now. The original proposal would have meant 
that rvalue references like C++ were possible (without conflating it 
with const).


But current auto ref is what we have, so I would recommend using it.

-Steve


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread Seb via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 23:27:42 UTC, H. S. Teoh wrote:
On Wed, Jan 10, 2018 at 12:18:46AM +0100, Timon Gehr via 
Digitalmars-d-learn wrote:

On 09.01.2018 22:04, H. S. Teoh wrote:
> [...]

I think "if (0 == 3) { static break; }" should be a 
compile-time error.


That's also a possible solution, perhaps a better solution than 
what I described.  Make it so that static break/continue cannot 
be nested inside runtime conditionals.  That should exclude all 
of the pathological cases, hopefully.



T


FWIW I recently bumped into a problem where `static break` would 
be _really_ useful:


https://github.com/dlang/dmd/pull/7577#discussion_r159175229


Re: Is there a way to get this associative array initialization to work?

2018-01-09 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/9/18 6:05 PM, WhatMeWorry wrote:

enum SoundType { MUSIC = 0, SOUND_EFFECT };

struct Sound
{
     string file;
     SoundType  musicOrSfx;
     void*  ptr;   // Mix_Chunk* for sfx;  Mix_Music* for music;
}

immutable Sound[string] soundLibrary  =   // line 148
[
     "SCRATCH"  : { file : "scratch.wav", musicOrSfx : 
SOUND_EFFECT, ptr : null },
     "BACKGROUND_TRACK" : { file : "beat.wav",    musicOrSfx : 
MUSIC,    ptr : null },
     "HIGH" : { file : "high.wav",    musicOrSfx : 
SOUND_EFFECT, ptr : null }

];


I keep getting a
source\app.d(148,1): Error: not an associative array initializer




https://issues.dlang.org/buglist.cgi?list_id=218715=not%20an%20associative%20array%20initializer_type=allwordssubstr_format=advanced=---

Note, I think you need at least Sound.SOUND_EFFECT, etc.

This bug looks particularly relevant: 
https://issues.dlang.org/show_bug.cgi?id=11221


I think it should really work.

-Steve


Re: Help optimizing UnCompress for gzipped files

2018-01-09 Thread Christian Köstlin via Digitalmars-d-learn
On 07.01.18 14:44, Steven Schveighoffer wrote:
> Not from what I'm reading, the C solution is about the same (257 vs.
> 261). Not sure if you have averaged these numbers, especially on a real
> computer that might be doing other things.
yes you are right ... for proper benchmarking proper statistics should
be in place, taking out extreme values, averaging them, ...

> Note: I would expect it to be a tiny bit faster, but not monumentally
> faster. From my testing with the reallocation, it only reallocates a
> large quantity of data once.
> 
> However, the D solution should be much faster. Part of the issue is that
> you still aren't low-level enough :)
> 
> Instead of allocating the ubyte array with this line:
> 
> ubyte[] buffer = new ubyte[200*1024*1024];
> 
> Try this instead:
> 
> // from std.array
> auto buffer = uninitializedArray!(ubyte[], 200*1024*1024);
thanks for that ... i just did not know how to get an uninitialized
array. i was aware, that dlang is nice and puts init there :)

> Yes! I am working on doing just that, but haven't had a chance to update
> the toy project I wrote: https://github.com/schveiguy/jsoniopipe
> 
> I was planning actually on having an iopipe of JsonItem, which would
> work just like a normal buffer, but reference the ubyte buffer underneath.
> 
> Eventually, the final product should have a range of JsonValue, which
> you would recurse into in order to parse its children. All of it will be
> lazy, and stream-based, so you don't have to load the whole file if it's
> huge.
> 
> Note, you can't have an iopipe of JsonValue, because it's a recursive
> format. JsonItems are just individual defined tokens, so they can be
> linear.
sounds really good. i played around with
https://github.com/mleise/fast/blob/master/source/fast/json.d ... thats
an interesting pull parser with the wrong licence unfortunately ... i
wonder if something like this could be done on top of iopipe instead of
a "real" buffer.

---
Christian Köstlin


Creating Struct for an output of a program.

2018-01-09 Thread Vino via Digitalmars-d-learn

Hi All,

 Request your help on how to create a struct with the output of 
the below program.


Program:
import std.algorithm: all, map, filter;
import std.stdio: File, writeln;
import std.typecons: Tuple, tuple;
import std.container.array;
import std.string: split, strip;
import std.uni: isWhite, toLower;
import std.range: chunks;

void main () {
Array!string TableData, StructureData;
auto Meta = 
File("C:\\Users\\bheev1\\Desktop\\Current\\Script\\Others\\meta\\meta.txt", "r");

auto MetaData = Array!(Tuple!(string, string))(Meta.byLineCopy()
.filter!(line => !line.all!isWhite)
.map!(a => a.split(":"))
.map!(a => tuple(a[0].toLower.strip, a[1].toLower.strip)));
foreach (line; MetaData[]) { TableData.insertBack(line[0]); 
StructureData.insertBack(line[1]); }

for(int i = 0; i < TableData[].length; i++ ) {
auto S1 = StructureData[i].split(",").chunks(3);
auto S2 = S1.map!(a => tuple(a[0],a[1],a[2]));
for(int z =0; z < S2.length; z++)
{ writefln("%-8s %;s", S2[z][1] , S2[z][0]); }
}
}

Output:
string name;
string country;
int age;


Need to create as struct using the output

struct Layout {
{
string name;
string country;
int age;

}

From,
Vino.B




Storing struct in a array

2018-01-09 Thread Vino via Digitalmars-d-learn

Hi All,

 It is possible to store struct in a array ans use the same in 
csvReader e.g.


import std.stdio;
import std.container.array;

void main () {
Array!string a;
struct Layout { string name; int value; double other; }

a.insert(Layout);
auto record =  
uFile.byLineCopy().joiner("\n").csvReader!(Tuple!a[0]))

foreach (record; records)
{
writeln(record.name);
writeln(record.value);
writeln(record.other);
}

From,
Vino.B


Re: Creating Struct for an output of a program.

2018-01-09 Thread Mengu via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 07:57:19 UTC, Vino wrote:

Hi All,

 Request your help on how to create a struct with the output of 
the below program.


Program:
import std.algorithm: all, map, filter;
import std.stdio: File, writeln;
import std.typecons: Tuple, tuple;
import std.container.array;
import std.string: split, strip;
import std.uni: isWhite, toLower;
import std.range: chunks;

void main () {
Array!string TableData, StructureData;
auto Meta = 
File("C:\\Users\\bheev1\\Desktop\\Current\\Script\\Others\\meta\\meta.txt", "r");

auto MetaData = Array!(Tuple!(string, string))(Meta.byLineCopy()
.filter!(line => !line.all!isWhite)
.map!(a => a.split(":"))
.map!(a => tuple(a[0].toLower.strip, a[1].toLower.strip)));
foreach (line; MetaData[]) { TableData.insertBack(line[0]); 
StructureData.insertBack(line[1]); }

for(int i = 0; i < TableData[].length; i++ ) {
auto S1 = StructureData[i].split(",").chunks(3);
auto S2 = S1.map!(a => tuple(a[0],a[1],a[2]));
for(int z =0; z < S2.length; z++)
{ writefln("%-8s %;s", S2[z][1] , S2[z][0]); }
}
}

Output:
string name;
string country;
int age;


Need to create as struct using the output

struct Layout {
{
string name;
string country;
int age;

}

From,
Vino.B


if S2 consists of data for Layout struct, then you can simply do:

auto S2 = S1.map!(a => Layout(a[0], a[1], a[2]));

which will give you a range of Layout.


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/8/18 9:27 AM, H. S. Teoh wrote:

On Sun, Jan 07, 2018 at 10:39:19PM -0500, Steven Schveighoffer via 
Digitalmars-d-learn wrote:

On 1/6/18 6:25 PM, Ali Çehreli wrote:

Is 'static foreach' sufficient for all needs or is there any value
for regular foreach over compile-time sequences?


If you use continues or breaks, then you need to switch to gotos if
using static foreach, as it does not support them directly.

[...]

Are you sure?  I was under te impression that it does support continues
and breaks -- but only if they are labelled, because of a syntactic
ambiguity otherwise.


I thought it only worked for constructs outside the static foreach (like 
switch).


testing...

Nope, doesn't work. The ambiguity is that if you have a breakable or 
continuable construct outside a static foreach (e.g. switch), then you 
may believe that the break statement is affecting the foreach (in fact, 
that is how tuple-foreach works), but you are actually affecting the 
outer construct. The extra requirement is to help you realize the 
implication. It may be removed in the future.


I may have been misleading when I made my first comment. What I mean is 
that you *can't* break or continue a static foreach, even with labels. 
However, you *can* do it to a standard foreach over a tuple. This may be 
one reason you want to use a tuple-foreach over a static foreach.


-Steve


Re: Is old style compile-time foreach redundant?

2018-01-09 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/8/18 3:07 PM, Jonathan M Davis wrote:

But regardless, labeled break definitely works within a static foreach, and
I expect that a labeled continue does as well, but I haven't tried it.


I didn't mean it that way, see my reply to H.

-Steve


Re: Storing struct in a array

2018-01-09 Thread Vino via Digitalmars-d-learn

On Tuesday, 9 January 2018 at 13:49:41 UTC, Vino wrote:

Hi All,

 It is possible to store struct in a array ans use the same in 
csvReader e.g.


import std.stdio;
import std.container.array;

void main () {
Array!string a;
struct Layout { string name; int value; double other; }

a.insert(Layout);
auto record =  
uFile.byLineCopy().joiner("\n").csvReader!(Tuple!a[0]))

foreach (record; records)
{
writeln(record.name);
writeln(record.value);
writeln(record.other);
}

From,
Vino.B


Hi All,

 Was able to find on hot to store a struct in an array, but not 
able to use that array in csvReader


Program:
import std.algorithm: joiner;
import std.container.array;
import std.csv: csvReader;
import std.stdio: File, writeln;
import std.typecons: Tuple, tuple;

void main () {
auto fName = 
"C:\\Users\\bheev1\\Desktop\\Current\\Script\\Others\\Table1.csv";

auto uFile = File(fName, "r");
struct T1 { string Name; string Country; int Age; }
Array!T1 T1s;
foreach (record; 
uFile.byLineCopy().joiner("\n").csvReader!(Tuple!T1s))

writeln(record);
}

Error:
C:\D\dmd2\windows\bin\..\..\src\phobos\std\typecons.d(523): 
Error: template instance parseSpecs!(T1s) cannot use local 'T1s' 
as parameter to non-global template

 parseSpecs(Specs...)
C:\D\dmd2\windows\bin\..\..\src\phobos\std\typecons.d(635): 
Error: CTFE failed because of previous errors in injectNamedFields
ArrayStruct.d(12): Error: template instance 
ArrayStruct.main.Tuple!(T1s) error instantiating

Failed: ["dmd", "-v", "-o-", "ArrayStruct.d", "-I."]

From,
Vino.B