Re: drepl fails because of missing lib linenoise

2016-12-08 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 8 December 2016 at 12:31:01 UTC, Nordlöw wrote:

drepl fails to build as

https://github.com/drepl/drepl/issues/58

Any ideas why?


Looks like you don't have liblinenoise installed.

Some basic notes on how to install on linux/macosx can be found 
here:

https://github.com/BlackEdder/todod#linenoise


Re: Compiling and linking libraries

2016-11-16 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 16 November 2016 at 14:27:41 UTC, Darren wrote:

Hey all,

This is a very beginner problem, but not one I know how to do 
on my own.  Could anyone give a step-by-step guide on how to 
compile libraries, and then use them in my project with DUB?


If you are happy to use dub I would just add the GL library as a 
dependency to my dub.json file. Then if you call dub it will 
download and compile the necessary file.


Example dub.json file:
```
{
"name": "myWindow",
"authors": [
"Darren"
],
"description": "A minimal D application.",
"copyright": "Copyright © 2016, Darren",
"dependencies": {
"derelict-gl3": "~>2.0.0-alpha.2"
}
}
```

This will build the necessary library into your library though, 
so it is not the same as using a static library.


Also see the "Creating an own project" section on 
https://code.dlang.org/getting_started


Re: problem with isnan

2016-11-11 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Thursday, 10 November 2016 at 23:45:01 UTC, Charles Hixson 
wrote:
you might try using std.math.isNaN instead and see what it 
does.



It was default initialized by the class instance:

classCell
...
floatcurActivation;
...

The this method doesn't have any mention of a few variables 
that are supposed to be default initialized, or which 
curActivation is one.



std.math.isNaN should work for the default initialization (at 
least it does for doubles)




Re: Combining "chunkBy" and "until" algorithms

2016-11-04 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 4 November 2016 at 08:04:12 UTC, Jacob Carlborg wrote:
Currently I'm using a standard for loop iterating over the 
lines. I'm always looking at the current line and the next 
line. When the current line is the standard pattern and the 
next line is is not, I do a separate loop until I see a 
standard pattern again, collecting the lines with the 
non-standard pattern in an array.


Could you filter [1] for the non standard pattern? Filter is 
lazy, so will only start looking for the next when the current 
one has been "handled".


[1] https://dlang.org/phobos/std_algorithm_iteration.html#.filter



Re: Avoiding GC

2016-10-26 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 26 October 2016 at 08:18:07 UTC, hardreset wrote:
Is there a page somewhere on how to program D without using the 
GC? How do I allocate / free structs / classes on the heap 
manually? New would be GCed memeory wouldnt it? Delete is being 
depreciated?


thanks.


There is the following:
https://wiki.dlang.org/Memory_Management


Re: From Python to Dlang

2016-10-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 18 October 2016 at 12:03:54 UTC, Alfred Newman wrote:

Hello and greetings,

I'm a brand new D developer coming from Python.

So, can you pls guys suggest me any resource like "D for a 
Python Developer" or so ? BTW, I just ordered the "D 
Programming Language" book from AA.


Cheers


Another great book, available for free online:
http://ddili.org/ders/d.en/index.html


Re: polar coordinates with ggplotd

2016-09-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Sunday, 18 September 2016 at 22:13:35 UTC, brocolis wrote:

Found an error in ys line. Thanks.


Does that mean you solved it?

Currently there is no special support for other coordinate 
systems, but I recently added Guides for x/y coordinates which 
should make this relatively straightforward to implement and is 
next on the list. Not sure when I'll get a chunk of time to 
implement it though.


For now you will have to convert the coordinates yourself, before 
plotting them.




Re: Draw math formulas with ggplotd

2016-09-17 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Saturday, 17 September 2016 at 11:57:17 UTC, John Colvin wrote:
On Saturday, 17 September 2016 at 11:45:07 UTC, Edwin van 
Leeuwen wrote:

But I assumed he meant adding the formula onto the plot.


Hah, yes, I should have read the question better.


Rereading the question I am actually not sure which of us 
interpreted the question correctly :)


Do you support embedding outside images? When I wanted nice 
mathematical notation generated quickly in D I have used pyd to 
call matplotlib's builtin math rendering (much quicker than a 
full latex roundtrip).


You can draw onto any cairo surface, so this should be possible. 
You'd just need to figure out how to cast/convert a matplotlib 
image to a cairo image.


Re: Draw math formulas with ggplotd

2016-09-17 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Saturday, 17 September 2016 at 11:22:04 UTC, John Colvin wrote:

On Saturday, 17 September 2016 at 02:41:15 UTC, brocolis wrote:
How do I draw math formulas programmatically? I want to do on 
screen what latex does on .pdf.


And I want to draw a math formula in the image generated with 
ggplotd.


Generate data from those formulas (I like to do this with 
something like iota(0, 10, 0.05).map!(x => sqrt(x) / (1 + 
sin(x)^^2)) and then plot that.


For this part ggplotd does have a helper function:

http://blackedder.github.io/ggplotd/ggplotd/stat.html#statFunction

auto gg = statFunction(x => sqrt(x) / (1 +
  sin(x)^^2), 0.0, 10).geomLine().putIn(GGPlotD());

But I assumed he meant adding the formula onto the plot.


Re: Draw math formulas with ggplotd

2016-09-17 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Saturday, 17 September 2016 at 09:56:09 UTC, Edwin van Leeuwen 
wrote:

On Saturday, 17 September 2016 at 02:41:15 UTC, brocolis wrote:
How do I draw math formulas programmatically? I want to do on 
screen what latex does on .pdf.


And I want to draw a math formula in the image generated with 
ggplotd.


You can't at the moment. Parsing latex equations is not a 
trivial task.


When I say you can't I meant that this is not explicitly 
supported by ggplotd.


Re: Draw math formulas with ggplotd

2016-09-17 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Saturday, 17 September 2016 at 02:41:15 UTC, brocolis wrote:
How do I draw math formulas programmatically? I want to do on 
screen what latex does on .pdf.


And I want to draw a math formula in the image generated with 
ggplotd.


You can't at the moment. Parsing latex equations is not a trivial 
task.


One possible approach would be to convert part of the equations 
(greek alphabet etc.) to utf and use geomLabel to "simulate" 
sub/super script. One caveat with this is that I am not sure how 
well cairo(d) supports utf.


Re: Checking all elements are unique.

2016-08-31 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Wednesday, 31 August 2016 at 07:40:39 UTC, Dorian Haglund 
wrote:

Hello,

I have an array of objects of class C which contain a id member.
I want to figure out if all the id members are unique using 
functional primitives.


For example, if I have:

class C
{
  int id;
}

and an array of C 'Cs';

My idea was to do:

auto ids = Cs.map!(c => c.id);
assert(equal(ids.sort().uniq(), ids.sort()));

But it doesn't compile because I can't can call sort on ids.

Any idea why ? and how to solve my initial problem, which is to 
check all ids are unique.


Regards,

Dorian


Sort require an indexable array. You can convert an insertRange 
to an indexable array with .array:

ids.array.sort()

You can also directly sort on id
Cs.array.sort!((a,b) => a.id < b.id);



Re: Serialize/Deserialize Tuple

2016-08-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 19 August 2016 at 09:55:32 UTC, Steve Biedermann wrote:
I'm trying to send data over the network. On the receiving 
side, I need a tuple of the sent values. Is there any way to 
achieve this?


Depends on the format the data is send in. There are a number of 
serialization/deserialization libraries:


binary:
https://github.com/atilaneves/cerealed

Others:
http://code.dlang.org/search?q=serial+painlessjson+cerealed



Re: Command Line Utility Library

2016-08-16 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 16 August 2016 at 13:32:26 UTC, Jacob Carlborg wrote:

On 2016-08-16 11:37, Seb wrote:


Manual work? O_o
Just open code.dlang.org and either hit CTRL-F or use the 
search bar
(Martin added elastic search two months ago) as the packages 
usually

have a very low PageRank.


It's a bit problematic when you don't know what to search for. 
Not all projects have a descriptive name ;)


Does it only search the description or also the README?


Re: Command Line Utility Library

2016-08-16 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 15 August 2016 at 07:29:58 UTC, UDW wrote:

Hi,

I would like some options for a library, preferably json 
configurable, that helps with command line tool development. 
Doesn't have to be in D specifically.




I am using:
http://code.dlang.org/packages/docopt

It's not really json configurable, but that shouldn't be to 
complex to implement yourself.


Re: Using external libraries the correct way

2016-07-17 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Sunday, 17 July 2016 at 17:52:59 UTC, solidstate1991 wrote:
Up to this day, I have to use them by dragging the source into 
my project. When I tried to import imageformats, the compiler 
looks up for the file imageformats.d and fails to finish the 
program.


I'm not using command line for compiling, I use Xamarin with 
mono-D instead.


I tend to use dub for all my external libraries:
http://code.dlang.org

Not sure how that ties in with mono-D though.


Re: Docs for `Group` type

2016-07-12 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 12 July 2016 at 11:40:48 UTC, Bahman Movaqar wrote:

On 07/12/2016 01:01 PM, Mike Parker wrote:

Do you have some sample code that shows the error?


Yes.  I'm working on Stockman[1] a playground to learn D.
In file `etl.d`, line 110 [2], if I change the line to
auto refInvoice = group[1].takeOne();
the file will not compile.  I have attached the compile error 
to this

message.

Thanks,


What does group.writeln; output? That should give you a good 
sense of what is going on.


Re: local const functions - bug ?

2016-07-07 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 7 July 2016 at 10:33:39 UTC, Basile B. wrote:

this compiles without error:


struct Foo
{
int i;
void bar()
{
void foo() const
{
i = 1;
}
foo;
}
}

In this case "const" seems to be a noop. Do you think it's a 
bug ? Shouldn't "const" be applied, despite of foo() 
inaccessibility ?


Is this related to:
https://issues.dlang.org/show_bug.cgi?id=1983


Re: Trying to get type and name at compile time

2016-05-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 24 May 2016 at 18:44:45 UTC, ag0aep6g wrote:


Seems to be a problem in ApplyLeft:


import std.meta: AliasSeq, ApplyLeft;
alias addType(T, string name) = AliasSeq!(T, name);
alias addTypeInt = ApplyLeft!(addType, int);
alias FullyInstantiated = addTypeInt!"foo";


Fails with: "std/meta.d(1114): Error: cannot interpret int at 
compile time".


I've filed an issue:
https://issues.dlang.org/show_bug.cgi?id=16070



Thanks! I've worked around it for now with some recursion :)

Using `is(...)` with an AliasSeq of only types is ok. But you 
can't use it when there's a non-type in the sequence.


That makes sense.

Thanks for the help, Edwin



Re: Trying to get type and name at compile time

2016-05-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 24 May 2016 at 15:09:43 UTC, Adam D. Ruppe wrote:
On Tuesday, 24 May 2016 at 15:01:33 UTC, Edwin van Leeuwen 
wrote:

// I expected AliasSeq!(double,"x")???
pragma(msg,test); // tuple((double), "x")


What Phobos calls AliasSeq is called tuple inside the compiler. 
They are the same thing, just different names.


That's what I assumed at first.. So why does the following fail 
with: cannot interpret double at compile time? I assumed 
staticMap would automatically flatten the resulting AliasSeqs.


```
import std.meta : AliasSeq, ApplyLeft, staticMap;

struct Point { double x; double y; }

template addType(T,alias name)
{
alias addType = AliasSeq!( typeof(__traits(getMember, Point, 
name)),

name );
}

alias test3 = addType!( Point, "x" );

// I expected AliasSeq!(double,"x")???
pragma(msg,test3); // tuple((double), "x")

//static assert(is(test == AliasSeq!(double,"x")));
alias ts = AliasSeq!("x","y");
alias addTypeP = ApplyLeft!(addType,Point);
alias mapped = staticMap!(addTypeP,ts);

pragma(msg,mapped);

void main() {
}
```

Looking at it now, I guess it is because staticMap does not work 
with alias values, only with actual type lists. Is that correct? 
Any ideas on how to do this?





static assert(is(test == AliasSeq!(double,"x")));


AliasSeq is not comparable as a type. You can test the 
individual pieces of it (`is(test[0] == double) && test[1] == 
"x"`) or wrap it in a struct or something.


I thought so, but a lot of the documentation does seem to compare 
it (see the example here):

https://dlang.org/library/std/meta/static_map.html





Trying to get type and name at compile time

2016-05-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

Hi all,

I am trying to get the type and name of a field at compile time, 
but can't get the following to work. Anyone any idea of why test 
is not of the type AliasSeq!(double, "x")?



```
import std.meta : AliasSeq;

struct Point { double x; double y; }

alias test = AliasSeq!(
typeof(__traits(getMember, Point, "x")),
"x"
);

// I expected AliasSeq!(double,"x")???
pragma(msg,test); // tuple((double), "x")

static assert(is(test == AliasSeq!(double,"x")));

void main() {}
```

Cheers, Edwin


Re: static member and/or @property ?

2016-05-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 19 May 2016 at 15:12:44 UTC, Edwin van Leeuwen wrote:

On Thursday, 19 May 2016 at 15:04:00 UTC, chmike wrote:
The only viable solution I found so far is by using distinct 
member names. In the interface we define name as a property, 
and in the class we define the static member with another 
name. Is it possible to avoid the different names ?


Can you use identifier!(typeof(this)) or something along those 
lines. I am not sure how it behaves with inheritance.


https://dlang.org/spec/traits.html#identifier


Sorry I meant __traits(identifier, typeof(this)).


Re: static member and/or @property ?

2016-05-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 19 May 2016 at 15:04:00 UTC, chmike wrote:
The only viable solution I found so far is by using distinct 
member names. In the interface we define name as a property, 
and in the class we define the static member with another name. 
Is it possible to avoid the different names ?


Can you use identifier!(typeof(this)) or something along those 
lines. I am not sure how it behaves with inheritance.


https://dlang.org/spec/traits.html#identifier


Re: Compile Tango for DMD2 - Any instructions how to do it?

2016-05-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 18 May 2016 at 16:37:48 UTC, TheDGuy wrote:

On Wednesday, 18 May 2016 at 16:13:35 UTC, Seb wrote:
May I ask why you need to get tango working? It has been 
deprecated a long time ago and phobos (the standard library) 
or alternatively other packages on dub have a look of features 
:)


Okay, it looks like 'onyx' is a library which handles serial 
communication in D. So tried to create a new project with DUB 
and add onyx as dependency but there are still some errors:


http://pastebin.com/4eRBt6XX

Any idea what i do wrong?


The onyx README seems to suggest it only works for POSIX. Did you 
try serial-port by any chance:

http://code.dlang.org/packages/serial-port

That does mention Windows as supported. It is quite old though, 
the latest github activity is from a year ago.


Re: static import (v2.071.0)

2016-05-11 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 11 May 2016 at 14:24:03 UTC, Chris wrote:

I was wondering if

`static import std.file;`

`if (exists(file))`

will only import `std.file.exists` or the whole lot of 
`std.file`? I want to find out what the best strategy for 
imports is now.


I tend to do specified imports, although (AFAIK) it doesn't make 
a difference for the imported code:


private import std.file : exists;

if (exists(file))




Re: ggplotd - curve colour

2016-05-09 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 9 May 2016 at 02:29:47 UTC, brocolis wrote:

Is this correct usage?
auto gg = GGPlotD().put( geomLine( Aes!(typeof(xs), "x", 
typeof(ysfit), "y", string, "colour")( xs, ysfit, "red") ) );


The output is a blank png file.

Full source:
import ggplotd.ggplotd;
import ggplotd.geom;
import ggplotd.aes;
import ggplotd.axes;

void main()
{
import std.array : array;
import std.algorithm : map;
import std.range : iota;
import ggplotd.colour;

auto f = (double x) { return x; };
auto xs = iota(-5, 5, 0.1 ).array;
auto ysfit = xs.map!((x) => f(x)).array;
auto gg = GGPlotD().put( geomLine( Aes!(typeof(xs), "x", 
typeof(ysfit), "y", string, "colour")( xs, ysfit, "red") ) );


gg.put( xaxisOffset( 0) ).put( yaxisOffset( 0) );
gg.save( "axes.png", 500, 300 );
}


The problem there is that colour also needs to be an InputRange. 
This is so that different points can have a different colours 
associated with it, which is particularly useful if you want to 
plot some data and have different types of data plotted as 
different colours.


In your example you can either do:

```
auto colour = "red".repeat( xs.length );
auto gg = GGPlotD().put( geomLine( Aes!(typeof(xs), "x",
 typeof(ysfit), "y", typeof(colour), "colour")( xs, ysfit, 
colour) ) );

```

Or use the mergeRange function mentioned before, which will 
automatically repeat if one argument is a single element.


```
auto aes = Tuple!( string, "colour" )( "red" ).mergeRange( 
Aes!(typeof(xs), "x",

 typeof(ysfit), "y" )( xs, ysfit ) );
```


Re: ggplotd - curve colour

2016-05-08 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Sunday, 8 May 2016 at 01:50:38 UTC, brocolis wrote:

How do I set the color of a curve with ggplotd?
Thanks.


Also see the below example on how to merge Colour with an 
existing range of points using mergeRange:


(Copied from http://blackedder.github.io/ggplotd/stat.html)

void main()
{
  /// http://blackedder.github.io/ggplotd/images/function.png
  import std.random : uniform;
  import std.typecons : Tuple;
  import ggplotd.stat : statFunction;
  import ggplotd.ggplotd : GGPlotD;
  import ggplotd.geom : geomLine, geomPoint;
  import ggplotd.aes : mergeRange;

  auto f = (double x) { return x / (1 + x); };

  auto aes = statFunction(f, 0.0, 10);
  auto gg = GGPlotD().put(geomLine(aes));

  // Generate some noisy points
  auto f2 = (double x) { return x / (1 + x) * uniform(0.75, 
1.25); };

  auto aes2 = f2.statFunction(0.0, 10, 25);

  // Show points in different colour
  auto withColour = Tuple!(string, 
"colour")("aquamarine").mergeRange(aes2);

  gg = gg.put(withColour.geomPoint);

  gg.save("function.png");
}



Re: ggplotd - curve colour

2016-05-08 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Sunday, 8 May 2016 at 01:50:38 UTC, brocolis wrote:

How do I set the color of a curve with ggplotd?
Thanks.


You can set colours by name:
https://github.com/BlackEdder/ggplotd/blob/master/source/ggplotd/colour.d#L20

Alternatively you can pass through the RGB value (see the link 
above for the specification).


Finally if you have multiple curves and don't want to specify 
specific colours you can just give them a different identifier 
(e.g. different double/int value (any type should do)) and it 
will chose the colours according to the colourgradient used. 
There is an example on how to specify your own gradient in the 
hist3D.svg example:

http://blackedder.github.io/ggplotd/ggplotd.html


Re: DUB and pragma lib - OSX

2016-04-20 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 05:53:28 UTC, Joel wrote:

How do I get this C stuff working with DUB?


Mind posting your dub configuration file?



Re: JSONValue floating and 42

2016-04-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 19 April 2016 at 13:44:08 UTC, Andre wrote:
-> I need to analyze every value whether it is a floating or an 
integer?


This is the correct option. Something like:

double f;
if (j["value"].type == JSON_TYPE.INTEGER)
  f = j["value"].integer.to!float;
else
  f = j["value"].floating;

There are also a number of libraries available that make dealing 
with json a bit easier:

code.dlang.org/search?q=json


Re: simple range question

2016-04-08 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 8 April 2016 at 18:27:59 UTC, Laeeth Isharc wrote:
suppose I have a forward or random access range.  what's the 
best way to compare each element with the element 4 elements 
prior to that element?  I could map each element to a tuple of 
the element and the element 4 bars previously and do it that 
way.  any neater way ?


I'd do it like this, but I guess that is what you mean with 
mapping it to a tuple:


zip( r, r[4..$] ).map!((t) => t[0] == t[1]);


Re: is std.algorithm.joiner lazy?

2016-04-07 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 7 April 2016 at 09:55:56 UTC, Puming wrote:

When compiled, I get the error:

Error: open path skips field __caches_field_0
source/app.d(19, 36): Error: template instance 
std.algorithm.iteration.cache!(MapResult!(__lambda1, int[])) 
error instantiating


That seems like a bug to me and you might want to submit it to 
the bug tracker. Even converting it to an array first does not 
seem to work:


import std.stdio : writeln;
import std.algorithm : map, cache, joiner;
import std.array : array;

auto read(int a) {
   return [0, a]; // second level
}

auto mkarray(int a) {
  return [-a, a].map!(x=>read(x)).cache.joiner; // to avoid 
calling read twice

}

void main() {
  auto xs = [1,2 ,3, 4];
  auto r = xs.map!(x=>mkarray(x)).array;

  // Both lines below should be equal, but second does not compile
  [[0, -1, 0, 1], [0, -2, 0, 2], [0, -3, 0, 3], [0, -4, 0, 
4]].cache.joiner.writeln;

  r.cache.joiner.writeln;
}

Above results in following error:
/opt/compilers/dmd2/include/std/algorithm/iteration.d(326): 
Error: one path skips field __caches_field_0
/d617/f62.d(19): Error: template instance 
std.algorithm.iteration.cache!(Result[]) error instantiating


Re: is std.algorithm.joiner lazy?

2016-04-07 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 7 April 2016 at 08:17:38 UTC, Puming wrote:
On Thursday, 7 April 2016 at 08:07:12 UTC, Edwin van Leeuwen 
wrote:


OK. Even if it consumes the first two elements, then why does 
it have to consume them AGAIN when actually used? If the 
function mkarray has side effects, it could lead to problems.


After some testing it seems to get each element twice, calls 
front on the MapResult twice, on each element. The first two 
mkarray are both for first element, the second two for the 
second. You can solve this by caching the front call with:


xs.map!(x=>mkarray(x)).cache.joiner;


Re: is std.algorithm.joiner lazy?

2016-04-07 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 7 April 2016 at 07:07:40 UTC, Puming wrote:

Hi:

when I use map with joiner, I found that function in map are 
called. In the document it says joiner is lazy, so why is the 
function called?


say:

int[] mkarray(int a) {
   writeln("mkarray called!");
   return [a * 2]; // just for test
}

void main() {
   auto xs = [1, 2];
   auto r = xs.map!(x=>mkarray(x)).joiner;
}

running this will get the output:

mkarray called!
mkarray called!

I suppose joiner does not consume?

when I actually consume the result by writlen, I get more 
output:


mkarray called!
mkarray called!
[2mkarray called!
mkarray called!
, 4]

I don't understand


Apparently it works processing the first two elements at 
creation. All the other elements will be processed lazily.


Even when a range is lazy the algorithm still often has to 
"consume" one or two starting elements, just to set initial 
conditions. It does surprise me that joiner needs to process the 
first two, would have to look at the implementation why.


Re: how to parse a string into a phobos datatype with additional logic

2016-04-07 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 7 April 2016 at 07:45:06 UTC, yawniek wrote:

what is the way one is supposed to parse e.g. a
double of unixtime (as delived by nginx logs) into a SysTime?

currently i'm creating a wrapper struct around SysTime with 
alias this as:


https://gist.github.com/yannick/6caf5a5184beea0c24f35d9d4a4c7783

really ugly imho.

is there a better way to do this?


You can try this library:
https://code.dlang.org/packages/dateparser


Re: Read only delegate

2016-04-04 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 4 April 2016 at 11:39:55 UTC, Kagamin wrote:

On Monday, 4 April 2016 at 11:32:23 UTC, Rene Zwanenburg wrote:

https://issues.dlang.org/show_bug.cgi?id=1983


Bug 1983 is about usage of delegates after creation, 
restrictions during creation are enforced. AIU, OP wants to 
have const check during creation.


I think the underlying issue is the same. The problem seems to be 
that:
Unfortunately, there is no way to declare a const delegate (by 
which I mean, a delegate whose context pointer is typed const).


I actually discovered the problem, due to the hole it leaves in 
the const system, where I got different results calling a const 
method multiple times. The const method in question called a 
delegate that changed its context pointer, resulting in changes 
during calls.




Re: Read only delegate

2016-04-04 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 4 April 2016 at 11:32:23 UTC, Rene Zwanenburg wrote:
On Monday, 4 April 2016 at 08:10:10 UTC, Edwin van Leeuwen 
wrote:
Is there a way to make sure a delegate only reads state, 
without changing it? I tried annotating the delegate as const, 
but that does not seem to work.

```


Yeah this is a nasty old issue. The underlying problem is that 
a delegate's function and context pointers are completely 
untyped.


https://issues.dlang.org/show_bug.cgi?id=1983


Thanks for the reference, hopefully this will be resolved at some 
point :)




Re: Read only delegate

2016-04-04 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 4 April 2016 at 08:10:10 UTC, Edwin van Leeuwen wrote:
Is there a way to make sure a delegate only reads state, 
without changing it? I tried annotating the delegate as const, 
but that does not seem to work.




Note that annotating with pure also doesn't help. As a result we 
can have a pure delegate that returns different results every 
time it is called.


```D
void main()
{
import std.stdio : writeln;
auto r = [0,1,2,3];

auto f = delegate() const pure
{
import std.array : front, popFront;
r.popFront;
return r.front;
};

r.writeln; // [0,1,2,3]
auto f1 = f();
r.writeln; // [1,2,3]
assert( f() == f1 ); // Throws
}
```



Read only delegate

2016-04-04 Thread Edwin van Leeuwen via Digitalmars-d-learn
Is there a way to make sure a delegate only reads state, without 
changing it? I tried annotating the delegate as const, but that 
does not seem to work.


```D
void main()
{
import std.stdio : writeln;
auto r = [0,1,2,3];

auto f = delegate() const // Compiles even though we are 
changing r

{
import std.array : popFront;
r.popFront;
};

r.writeln; // [0,1,2,3]
f();
r.writeln; // [1,2,3]
}
```




Re: infer type argument in classe constructor?

2016-03-29 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 29 March 2016 at 10:13:28 UTC, Puming wrote:

Hi,

I'm writing a generic class:

```d

struct Message { ... }

class Decoder(MsgSrc) {
}
```

When using it, I'd have to include the type of its argument:

```
void main() {
   Message[] src = ...;

   auto decoder = new Decoder!(Message[])(src);

   ...
}
```

Can it be inferred so that I only need to write?

```d
auto decoder = new Decoder(src); // you can infer the type from 
src.

```


You can't directly. This is (AFAIK) because this()() can also be 
templated, making it impossible to just derive. The common way in 
D to deal with this/work around it is to create a helper function 
that can infer it:


```D
auto decoder(T)(T src)
{
  return new Decoder!T(src);
}

auto dec = decoder(src)
```

This pattern is widely used in phobos (e.g. tuple and Tuple)


Re: Usage of custom class with JSONValue

2016-03-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 24 March 2016 at 11:39:13 UTC, arturg wrote:

isnt alias this supposed to do this implicitly?

convert this
auto jsValue = JSONValue(new MyClass());

into this
auto jsValue = JSONValue((new MyClass())._data);


Good point, I did not catch that. That indeed should work and 
seems to be a bug. Does it work if _data is a base type (string 
or int, etc..)




Re: Usage of custom class with JSONValue

2016-03-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 24 March 2016 at 08:15:12 UTC, Andre wrote:

Hi,

I have a class which has already an alias this to a string 
array,

so I can use it in a foreach loop.

class MyClass
{
string[] _data;
alias _data this;
// ...
}

void main()
{
import std.json;
auto jsValue = JSONValue(new MyClass());
}

For some generic code I need an implicit conversion of MyClass 
so I can
use it for a JSONValue. For the coding above I receive a 
compiler error:

static assert  "unable to convert type "MyClass" to json"



JSONValue only works with the build in types, not with user 
defined types. Either you define a specific function for the 
class that returns a JSONValue. Easiest way to do that would be 
to build an associative array with strings as keys with the 
names, and JSONValues as values and turn that into JSONValue, 
i.e. (untested):

class MyClass
{
string[] _data;
alias _data this;
// ...
   JSONValue toJSON()
  {
JSONValue[string] aa;
JSONValue[] dataJSON = _data.map!((a) => JSONValue(a)).array;
aa["data"] = JSONValue(dataJSON);
return JSONValue(aa);
  }
}

Alternatively there are multiple serialization libraries that 
will allow you to turn any user defined type from and to 
JSONValues.


https://code.dlang.org/packages/painlessjson
https://code.dlang.org/packages/jsonizer

Cheers, Edwin


Re: iota result as member variable

2016-03-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 24 March 2016 at 06:54:25 UTC, Alex wrote:

Hi everybody,
doing some optimization on my code, I faced some strange 
question:

how to save a iota result in a class member?

Say I have
class A
{
??? member;

auto testIter4()
{
return iota(0,5);
}
}

void main()
{
A a = new A();
a.member = testIter4();
}

how would I declare the member?



Yeah this is one of the downsides of voldermort types. In these 
cases typeof and ReturnType are your friend. It often takes me a 
couple of tries to get it right, but the following seems to work:


import std.traits : ReturnType;
import std.range : iota;
class A
{
ReturnType!(A.testIter4) member;
auto testIter4()
{
return iota(0,5);
}
}

void main()
{

 A a = new A();
 a.member = a.testIter4();

}


Re: Something wrong with GC

2016-03-22 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 22 March 2016 at 13:46:41 UTC, stunaep wrote:

public class Example2 {

private int one;
private int two;

public this(int one, int two) {
this.one = one;
this.two = two;
}
}


in a tree map and list of some sort. Neither of the above work 
whether they are classes or structs and it's starting to become 
quite bothersome...


Is there a particular reason why you don't want to use the 
standard ranges?


public class Example2 {

private int one;
private int two;

public this(int one, int two) {
this.one = one;
this.two = two;
}
}

void main()
{
auto myExamplesList = [ new Example2( 6,3 ), new Example2(7,5) ];

// Note that if you do a lot of appending then using 
Appender is more performant than ~=

myExamplesList ~= new Example2(9,1);
}

For trees there is also redBlackTree




Re: Gdmd compiling error

2016-03-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 12:17:42 UTC, Orkhan wrote:

On Tuesday, 15 March 2016 at 18:26:48 UTC, Ali Çehreli wrote:

I don't know where from shpuld I get help. Thanks.


Is the xcomm library available somewhere, maybe if we had a link 
to the original documentation we could help.




Re: Obtaining argument names in (variadic) functions

2016-03-19 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 16 March 2016 at 20:53:42 UTC, JR wrote:



void printVars(Args...)()
if (Args.length > 0)
{
import std.stdio : writefln;

foreach (i, arg; Args) {
writefln("%s\t%s:\t%s", typeof(Args[i]).stringof, 
Args[i].stringof, arg);

}
}

void main() {
int abc = 3;
string def = "58";
float ghi = 3.14f;
double jkl = 3.14;

printVars!(abc,def,ghi,jkl)();
}


Interesting, any idea if it is possible to do assignment within 
template.. Either:


printVars!(int abc=5,string def="58")();
or something like
printVars!("abc","def",ghi)(5,"58");



Re: Obtaining argument names in (variadic) functions

2016-03-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 17 March 2016 at 13:53:00 UTC, JR wrote:


Interesting, any idea if it is possible to do assignment 
within template.. Either:


printVars!(int abc=5,string def="58")();
or something like
printVars!("abc","def",ghi)(5,"58");


What would the use-cases for those be?

I don't think the first is valid grammar, and I'm not sure what 
you want the second to do. Resolve symbols by string literals 
of their names? That might need a string mixin as they wouldn't 
be in scope when in the called template function, but I've 
never tried it.


Both use cases are when you want a named parameter, without 
having to assign it first. I know the first is not valid grammar, 
was just wondering if you might be smarter than me and see a way 
to make it valid :)


Second one is another possible alternative that I have been 
thinking about.


Basically, say I want to have the named (optional) parameters x 
and y. In your initial example I would be required to do:


```
int x = 1;
string y = "2";
doSomethingWithNamedPars!(x,y)();
```

I just hoped to shorten that to a one liner similar to:

```
doSomethingWithNamedPars!(x=1,y="2")();
```

or alternatively

```
doSomethingWithNamedPars!("x","y")(1,"2");
```

(where doSomethingWithNamedPars's behaviour depends on which 
named parameters it is passed)


Just as a reference, my current approach (in ggplotd) is with 
named tuples, but that is slightly more verbose than I had hoped:


```
doSomethingWithNamedPars( Tuple!(int, "x", string, "y")( 1, 2 ) );
```


Re: How to sort a range

2016-03-09 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 9 March 2016 at 15:39:55 UTC, rcorre wrote:

On Wednesday, 9 March 2016 at 14:28:11 UTC, cym13 wrote:

Still curious as to why it fails; maybe the range is getting 
copied at some point? I guess I need to step through it.


I did try different SwapStrategies with no luck.


Since you are adapting phobos anyway you could try commenting out 
the assert and see what the result of the sort is. That might 
give you some clue:


//assert(isSorted!lessFun(r), "Failed to sort range of type " ~ 
Range.stringof);



Also I notice the line numbering is different in my sorted.d 
file. Did you test the latest version of dmd/phobos?





Re: How to sort a range

2016-03-09 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 9 March 2016 at 13:04:31 UTC, rcorre wrote:
On Wednesday, 9 March 2016 at 12:31:18 UTC, Edwin van Leeuwen 
wrote:

On Wednesday, 9 March 2016 at 12:21:55 UTC, rcorre wrote:
If you are looking for a lazy uniq that works on non sorted 
ranges, I implemented one not to long ago:

http://github.com/BlackEdder/ggplotd/blob/master/source/ggplotd/range.d


That sounds like the kind of thing I was looking for. I'll 
take a look, thanks!


Well that one does allocate, because it keeps track of which 
values have already been seen.


Yup, just noticed that >.<


Of course it only allocates when the actual result is used, so 
this will probably be more efficient if you only need a small 
number of unique results or need to keep the unsorted range 
around/intact. Sorting without allocating and then using uniq 
should indeed be more efficient in other cases.


Did you try different SwapStrategy values in your original?


Re: How to sort a range

2016-03-09 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 9 March 2016 at 12:21:55 UTC, rcorre wrote:
If you are looking for a lazy uniq that works on non sorted 
ranges, I implemented one not to long ago:

http://github.com/BlackEdder/ggplotd/blob/master/source/ggplotd/range.d


That sounds like the kind of thing I was looking for. I'll take 
a look, thanks!


Well that one does allocate, because it keeps track of which 
values have already been seen.


Re: How to sort a range

2016-03-09 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 9 March 2016 at 03:05:52 UTC, rcorre wrote:
I was in a situation where I wanted to remove duplicates from 
an OnlyResult.
To do this with uniq, I needed to sort it. OnlyResult doesn't 
satisfy the template constraints of sort, but this seems easy 
enough to fix. I made front, back, and opIndex return by ref. 
With this, the following compiles:


assert(only(3,1,2).sort.equal(only(1,2,3)));

However, it fails with:

core.exception.AssertError@std/algorithm/sorting.d(1052): 
Failed to sort range of type OnlyResult!(int, 3LU)


So, if you have a range for which sort compiles, what does it 
take to make sorting actually work?


For reference, my two attempts were:

https://github.com/rcorre/phobos/commit/d89b3cfab7a0938e178a506b4ceb8faae6ecbfe2

https://github.com/rcorre/phobos/commit/512d9b8db6f311db6a9b6ccb077a691cec66ce70


I'm not sure why your fix didn't work, but generally I work 
around this by converting the OnlyResult into an array:


import std.array : array;
assert(only(3,1,2).array.sort.equal(only(1,2,3)));


If you are looking for a lazy uniq that works on non sorted 
ranges, I implemented one not to long ago:

http://github.com/BlackEdder/ggplotd/blob/master/source/ggplotd/range.d


Re: Memory Efficient HashSet

2016-03-08 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 8 March 2016 at 08:12:04 UTC, Nordlöw wrote:
Has anybody put together a memory-efficient D-implementation of 
a HashSet


Something like

sparse_hash_set<> contained in

https://github.com/sparsehash/sparsehash

but in D.


There is an implementation in:
code.dlang.org/packages/emsi_containers

But to be honest I got stuck trying to use it (copy constructor 
disabled), so I used this very minimal wrapper around associative 
array:


private struct HashSet(E) {
// TODO switch to proper implementation (not using AA)
bool put( E el )
{
if ( el in set )
return false;
set[el] = set.length;
return true;
}
size_t[E] set;
}

(I only needed put, since I used it to check whether we already 
encountered a value before in a lazy/non sorted implementation of 
uniq)


Re: Warning: statement is not reachable

2016-03-02 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 1 March 2016 at 21:30:44 UTC, Tamas wrote:

  foreach(attr; __traits(getAttributes, S)) {
static if (is(attr == Tag)) {
  return true;
}
  }
  return false;
}();
}

void main() {
  static @Tag struct MyStruct {}
  static struct VanillaStruct {}
  static assert(isTagged!MyStruct);
  static assert(!isTagged!VanillaStruct);
}


Sorry forgot to add the fix to the email. The following should 
work:


  bool tag = false;
  foreach(attr; __traits(getAttributes, S)) {
 static if (is(attr == Tag)) {
   tag = true;
 }
   }
   return tag;



Re: Warning: statement is not reachable

2016-03-02 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 1 March 2016 at 21:30:44 UTC, Tamas wrote:
My d code doesn't compile using ldc2 1.0.0-alpha or anything 
above DMD v2.068.0


Using these compilers I get a lot of "Warning: statement is not 
reachable". Then the both compiler crashes.


ldc2 -w reach.d
dmd -w reach.d

reach.d:

struct Tag {}

template isTagged(S) {
  enum bool isTagged =
delegate() {
  foreach(attr; __traits(getAttributes, S)) {
static if (is(attr == Tag)) {
  return true;
}
  }
  return false;
}();
}

void main() {
  static @Tag struct MyStruct {}
  static struct VanillaStruct {}
  static assert(isTagged!MyStruct);
  static assert(!isTagged!VanillaStruct);
}


We had the same problem in painlessjson and you can find some 
more background (with our fix) on it here: 
https://github.com/BlackEdder/painlessjson/issues/49


As I understand it: if attr == Tag the code will look something 
like this:


   foreach(attr; __traits(getAttributes, S)) {
   return true;
   }
   return false;

and the return false is basically unreachable.


Re: Why file.exists of relative path on Linux always return false?

2016-02-29 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 29 February 2016 at 14:58:46 UTC, Alex Parrill wrote:

On Monday, 29 February 2016 at 14:50:51 UTC, Suliman wrote:

I am trying to check relative path on Linux for exists.

string mypath = "~/Documents/imgs";


~ is expanded by your shell. It is not a relative path, and 
system calls do not recognize it (same with environmental 
variables).


D can expand tilde with expandTilde:

import std.path : expandTilde;
string mypath = expandTilde("~/Documents/imgs");




Re: Am I right understand the dub.json system?

2016-02-29 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 29 February 2016 at 12:45:36 UTC, Suliman wrote:
On Monday, 29 February 2016 at 12:34:02 UTC, Edwin van Leeuwen 
wrote:

Should it be like this?
http://www.everfall.com/paste/id.php?80k9jsgdx6o3

"versions": ["VibeCustomMain"],
"versions": ["USE_MYSQL"],



As far as I know all versions should be on one line:
 "versions": ["VibeCustomMain","USE_MYSQL"],


And by log it's again try to build sqllite.


What does the log actually say? Is it trying to bind to sqlite?



What happens if you also add

"subConfigurations": {
   "ddbc":"MySQL"
}


Re: Am I right understand the dub.json system?

2016-02-29 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 29 February 2016 at 12:27:04 UTC, Suliman wrote:
For example I have got app that depended on DDBC. In 
configuration section DDBC related on:


"libs-posix": [
"sqlite3",
"pq"
]

Does it's mean that it will try to find this 2 libs in any 
case? Even I do not use them.


If I do not need them what I should to do? Fix 
~/.dub/packages/ddbc and remove this strings from it, or what?


Reading the dub.json from ddbc it seems you can specify which 
version you want. So if you only need mysql support you add

"versions": ["USE_MYSQL"],
in your own dub.json file.


Re: Is DUB the best place to get examples of "Best of" D code?

2016-02-28 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Sunday, 28 February 2016 at 05:59:39 UTC, WhatMeWorry wrote:


If so, is there a way to do a global search of all projects in 
DUB?


If you just want to search through package names and descriptions 
you can use the search box at the top right of code.dlang.org.


If you want to search through code. Most packages are on github, 
so you could search there (limit by D projects).


Re: Installing DUB on OSX

2016-02-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 18 February 2016 at 09:25:00 UTC, Joel wrote:
On Thursday, 18 February 2016 at 08:24:34 UTC, Jacob Carlborg 
wrote:

On 2016-02-18 08:11, Joel wrote:
I had dub installed in a folder that meant I had to put 'sudo 
dub' to
run it. I've tried to fix the problem, but where do you put 
it (also I

tried one place, but couldn't put it in that folder)?


You usually have read access to most paths. That means you 
should be able to run dub without sudo. Where is "dub" 
located? Run "which dub".


It's currently in '/usr/local/bin'.

How do I add it to '/usr/bin' (or what ever)?

I get:
Joels-MacBook-Pro:Downloads joelcnz$ cp dub /usr/bin
cp: /usr/bin/dub: Operation not permitted


sudo cp dub /usr/bin/

but to be honest I would delete dub (sudo rm /usr/local/bin/dub) 
and then try to install it with homebrew again.


Re: String joining an array of structs or class instances implementing toString?

2016-02-11 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 11 February 2016 at 12:44:15 UTC, pineapple wrote:
It feels like there should be an out-of-the box way to do this 
but I haven't been able to find it? Help?


This is the thing that I want to do:

struct example{
const string str;
//this(string str){ this.str = str; }
string toString(){
return this.str;
}
}

public void main(){
import std.stdio;
import std.string;
example[] parts = [example("hello"), example("world")];
writeln(std.string.join(parts, " "));
}


I'd do it like this:

import std.algorithm : map;
pars.map!((part) => part.toString) // Turn them to strings
 .join(" ").writeln; // Join them.


Re: String joining an array of structs or class instances implementing toString?

2016-02-11 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 11 February 2016 at 13:43:49 UTC, pineapple wrote:
Thanks! Does the map function iterate without constructing an 
extra list in-memory?


Yes, it is lazy, so it only calls toString when the result is 
actually used (by the join call).



In case you do need to create an extra list you can use array as 
follows:


import std.array : array;
auto result = parts.map!((part) => part.toString).array;

The call to array will "force" it to construct an array out of it.




Re: Speed of csvReader

2016-01-22 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 22 January 2016 at 02:16:14 UTC, H. S. Teoh wrote:
On Thu, Jan 21, 2016 at 04:50:12PM -0800, H. S. Teoh via 
Digitalmars-d-learn wrote:

[...]
> >   https://github.com/quickfur/fastcsv

[...]

Fixed some boundary condition crashes and reverted doubled 
quote handling in unquoted fields (since those are illegal 
according to RFC 4810).  Performance is back in the ~1200 msec 
range.



T


That's pretty impressive. Maybe turn it on into a dub package so 
that data pulverizer could easily test it on his data :)


Re: Speed of csvReader

2016-01-21 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Thursday, 21 January 2016 at 09:39:30 UTC, data pulverizer 
wrote:

  StopWatch sw;
  sw.start();
  auto buffer = std.file.readText("Acquisition_2009Q2.txt");
  auto records = csvReader!row_type(buffer, '|').array;
  sw.stop();



Is it csvReader or readText that is slow? i.e. could you move 
sw.start(); one line down (after the readText command) and see 
how long just the csvReader part takes?


Re: Speed of csvReader

2016-01-21 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Thursday, 21 January 2016 at 15:17:08 UTC, data pulverizer 
wrote:

On Thursday, 21 January 2016 at 14:56:13 UTC, Saurabh Das wrote:
@Edwin van Leeuwen The csvReader is what takes the most time, 
the readText takes 0.229 s


The underlying problem most likely is that csvReader has (AFAIK) 
never been properly optimized/profiled (very old piece of the 
library). You could try to implement a rough csvReader using 
buffer.byLine() and for each line use split("|") to split at "|". 
That should be faster, because it doesn't do any checking.


Non tested code:
string[][] res = buffer.byLine().map!((a) => 
a.split("|").array).array;




Re: CMake support for D

2016-01-04 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Monday, 4 January 2016 at 12:40:23 UTC, Dibyendu Majumdar 
wrote:


Thanks for suggesting dub, will check it out. Also premake 
seems to support D so that is another option.




Another alternative is reggae which supports mixed code base: 
https://github.com/atilaneves/reggae and can generate 
ninja/make/tup build rules (similarly to cmake).




Re: my first D program (and benchmark against perl)

2015-11-11 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 11 November 2015 at 13:32:00 UTC, perlancar wrote:

for (int rownum=0; rownum < table.length; rownum++) {
res ~= "|";
for (int colnum=0; colnum < table[rownum].length; 
colnum++) {
res ~= leftJustify(table[rownum][colnum], 
widths[colnum]);

res ~= "|";
}
res ~= "\n";


Not sure if this will be faster, but you could try rewriting the 
above for loop

with more functional code (code below is untested):

table.map!((col)
  { return zip(col,widths)
  .map!( (e) => leftJustify(e[0], e[1] ) )
  .join("|");
  }).join("\n");

Cheers,

Edwin


Re: foreach loop

2015-11-03 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 3 November 2015 at 15:29:31 UTC, Namal wrote:

writefln("Count is: %s", arr
  .filter!(a => a==true)
  .sum);

// Note: std.algorithm.sum is the same as
// std.algorithm.reduce!((a,b)=a+b);




Shouldn't you be using walkLength instead of sum, since you are 
counting the left over values?


import std.range : walkLength;
writefln("Count is: %s", arr
  .filter!(a => a==false)
  .walkLength);



Re: foreach loop

2015-11-03 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 3 November 2015 at 16:55:44 UTC, wobbles wrote:
On Tuesday, 3 November 2015 at 15:42:16 UTC, Edwin van Leeuwen 
wrote:

On Tuesday, 3 November 2015 at 15:29:31 UTC, Namal wrote:

writefln("Count is: %s", arr
  .filter!(a => a==true)
  .sum);

// Note: std.algorithm.sum is the same as
// std.algorithm.reduce!((a,b)=a+b);




Shouldn't you be using walkLength instead of sum, since you 
are counting the left over values?


import std.range : walkLength;
writefln("Count is: %s", arr
  .filter!(a => a==false)
  .walkLength);


That would work also yes.
Be interesting to know which is more efficient actually - I 
suspect they're very similar.


false converts to zero, so
[false,false,false].sum == 0

Of course true converts to one ->
[true,true,true].sum == 3


Re: Merging two named Tuples

2015-10-29 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Saturday, 24 October 2015 at 11:04:14 UTC, Edwin van Leeuwen 
wrote:
I am trying to write a function to merge two named structs, but 
am completely stuck on how to do that and was wondering if 
anyone good provide any help. I know I can access the different 
names with tup.fieldNames, but basically can't work out how to 
use that to build the new return type. Below is an outline of 
what I am trying to do (with unittest). Any pointers would be 
greatly appreciated.


I tried the following, but get a compile error:
source/ggplotd/aes.d(633): Error: variable tup cannot be read at 
compile time
source/ggplotd/aes.d(633): Error: argument to mixin must be a 
string, not (__error)
source/ggplotd/aes.d(646): Error: template instance 
ggplotd.aes.merge!(Tuple!(string[], "x", string[], "y", string[], 
"label"), Tuple!(double[], "x", double[], "y")) error 
instantiating


import std.typecons : Tuple;
template merge(T, U)
{
auto merge( T base, U other )
{
string typing = "Tuple!(";
string variables = "(";
foreach( i, t; other.fieldNames )
{
typing ~= other.Types[i].stringof ~ ",\"" ~ t ~ "\",";
variables ~= "other." ~ t ~ ",";
}

foreach( i, t; base.fieldNames )
{
bool contains = false;
foreach( _, t2; other.fieldNames )
{
if (t==t2)
contains = true;
}
if (!contains)
{
typing ~= base.Types[i].stringof ~ ",\"" ~ t ~ 
"\",";

variables ~= "base." ~ t ~ ",";
}
}
string tup = typing[0..$-1] ~ ")" ~ variables[0..$-1] ~ 
");";

// Do some clever CTFE
return mixin(tup);
}
}

///
unittest
{
auto xs = ["a","b"];
auto ys = ["c","d"];
auto labels = ["e","f"];
auto aes = Tuple!(string[], "x", string[], "y", string[], 
"label")(

xs, ys, labels );

auto nlAes = merge( aes, Tuple!(double[], "x",
double[], "y" )(
[0,1], [3,4] ) );

assertEqual( nlAes.x[0], 0 );
assertEqual( nlAes.label.front, "e" );
}

I guess fieldNames does not exist at compile time? Can I get the 
fieldNames etc at compile time?


Cheers, Edwin


Re: Merging two named Tuples

2015-10-29 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 29 October 2015 at 19:42:10 UTC, anonymous wrote:
`tup` is an ordinary (run time, dynamic) string to the type 
system. You can't mixin those. You can only mixin static values 
(enum, static immutable, CTFE results).


The code you're generating doesn't depend on `base` and 
`other`. All it needs are `T` and `U`. So, you can generate the 
code from the types and mix it into a function that takes `T 
base, U other`:



Thanks :) That worked perfectly.


Merging two named Tuples

2015-10-24 Thread Edwin van Leeuwen via Digitalmars-d-learn
I am trying to write a function to merge two named structs, but 
am completely stuck on how to do that and was wondering if anyone 
good provide any help. I know I can access the different names 
with tup.fieldNames, but basically can't work out how to use that 
to build the new return type. Below is an outline of what I am 
trying to do (with unittest). Any pointers would be greatly 
appreciated.



/++
Merge two Aes structs

If it has similar named types, then it uses the second one.

Returns a new struct, with combined types.
+/
import std.typecons : Tuple;
template merge(T, U)
{
auto merge( T base, U other )
{
// Go over other.fieldNames and collect them for new tuple
// Go over base.fieldNames, ignoring the ones that other 
has as well

// Build newTuple
return newTuple;
}
}

///
unittest
{
auto xs = ["a","b"];
auto ys = ["c","d"];
auto labels = ["e","f"];
auto aes = Tuple!(string[], "x", string[], "y", string[], 
"label")(

xs, ys, labels );

auto nlAes = merge( aes, Tuple!(double[], "x",
double[], "y" )(
[0,1], [3,4] ) );

assertEqual( nlAes.x[0], 0 );
assertEqual( nlAes.label.front, "e" );
}



Re: Idiomatic adjacent_difference

2015-10-16 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Friday, 16 October 2015 at 11:43:16 UTC, Guillaume Chatelet 
wrote:

On Friday, 16 October 2015 at 11:38:35 UTC, John Colvin wrote:

Nice !
I wanted to use lockstep(r, r.dropOne) but it doesn't return a 
Range :-/

It has to be used in a foreach.


Instead of lockstep you can always use zip (which is the same but 
returns a range)



zip(r, r[1..$]).map!((t) => t[1]-t[0]);


Frequent cannot deduce function from argument types

2015-10-16 Thread Edwin van Leeuwen via Digitalmars-d-learn
Just wondering if anyone has any tips on how to solve/avoid 
"cannot deduce function from argument types" when relying on 
template programming.


I run into these problems all the time. Current one was when I 
tried:


```
auto ys = NumericLabel(groupedAes.front.map!((t)=>t.y));
```

NumericLabel is a pretty minimal templated InputRange, with as 
only requirement on the argument that it is also an InputRange. I 
then get the following compile error:


```
source/ggplotd/geom.d(83,35): Error: struct 
ggplotd.aes.NumericLabel cannot ded
uce function from argument types !()(MapResult!(__lambda2, 
FilterResult!(__lamb
da2, Aes!(double[], "x", double[], "y", string[], "colour", 
candidates are:
source/ggplotd/aes.d(515,1):ggplotd.aes.NumericLabel(T) 
if (isInputRang

e!T)
```

As far as I know MapResult always returns an input range and as 
you can see there is only one candidate of NumericLabel, so to be 
honest it looks relatively straightforward to me.


Now I can define the type specifically (and/or typeof) but it 
seems like there should be a better way.


In this case typeof isn't even happy:
```
source/ggplotd/geom.d(84,17): Error: constructor 
ggplotd.aes.NumericLabel!(MapResult!(__lambda2, 
FilterResult!(__lambda2, Aes!(string[], "x", string[], "y", 
string[], "colour".NumericLabel.this (MapResult!(__lambda2, 
FilterResult!(__lambda2, Aes!(string[], "x", string[], "y", 
string[], "colour"))) range) is not callable using argument types 
(MapResult!(__lambda3, FilterResult!(__lambda2, Aes!(string[], 
"x", string[], "y", string[], "colour"

```

If we look closely, it expects a __lambda2 as the MapResult 
argument, but it gets a __lambda3.



I am able to work around it by converting the mapresult to an 
array, but I'd rather use a lazy solution.







Re: Dub package with C code

2015-09-24 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Thursday, 24 September 2015 at 06:21:02 UTC, Sebastiaan Koppe 
wrote:
Because I want to focus on the product I am building right now, 
not on side-projects.


You could try including the c source in your repo and add 
preBuildCommands to the dub config which builds the static 
library. Alternatively you could use reggea to build both.


Re: ORM libraries for D

2015-09-24 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Thursday, 24 September 2015 at 13:24:14 UTC, Rikki Cattermole 
wrote:

Dvorm is more or less feature complete :)
I am the author of it, but unless issues come up I do not 
intend to continue working upon it.


You could consider bumping it up to version 1.0.0 to highlight 
this.





Re: reading file byLine

2015-09-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 18 September 2015 at 10:48:25 UTC, Namal wrote:
On Friday, 18 September 2015 at 10:34:41 UTC, Edwin van Leeuwen 
wrote:

On Friday, 18 September 2015 at 10:26:46 UTC, Namal wrote:
Hello guys, is there a nice functional way to read the file 
which is like



1,2,3,4,5,6
2,3,4,5,6,7
8,9,0,9,2,3

line by line, split numbers and remove each ','
convert it to int and save in a matrix int[][] arr?


Not tested, but I think the following should work:

auto matrix = str
  .byLine
  .map!((l) => l.split(",")// Split each line
.map!(to!int)  // Turn into ints
.array)// Return an array
  .array // Copy into an array


And how do tell here to read my file?


Replace str with File("myfile"):

auto matrix = File("myfile")
   .byLine
   .map!((l) => l.split(",")// Split each line
 .map!(to!int)  // Turn into ints
 .array)// Return an array
   .array // Copy into an array



Re: reading file byLine

2015-09-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 18 September 2015 at 10:26:46 UTC, Namal wrote:
Hello guys, is there a nice functional way to read the file 
which is like



1,2,3,4,5,6
2,3,4,5,6,7
8,9,0,9,2,3

line by line, split numbers and remove each ','
convert it to int and save in a matrix int[][] arr?


Not tested, but I think the following should work:

auto matrix = str
  .byLine
  .map!((l) => l.split(",")// Split each line
.map!(to!int)  // Turn into ints
.array)// Return an array
  .array // Copy into an array




Re: reading file byLine

2015-09-18 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 18 September 2015 at 12:28:29 UTC, Namal wrote:
So do I understand it right: does  => in map! indicates a 
lambda function?


Yes exactly. There are a number of ways you can define a lambda 
function in D. For example if the function is multiline I often 
use:

(l) {
   ...; // do something
   return result;
}

More details here http://ddili.org/ders/d.en/lambda.html (half 
way down the page)


Re: Speeding up text file parser (BLAST tabular format)

2015-09-14 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Monday, 14 September 2015 at 12:50:03 UTC, Fredrik Boulund 
wrote:
On Monday, 14 September 2015 at 12:44:22 UTC, Edwin van Leeuwen 
wrote:
Sounds like this program is actually IO bound. In that case I 
would not expect a really expect an improvement by using D. 
What is the CPU usage like when you run this program?


Also which dmd version are you using. I think there were some 
performance improvements for file reading in the latest 
version (2.068)


Hi Edwin, thanks for your quick reply!

I'm using v2.068.1; I actually got inspired to try this out 
after skimming the changelog :).


Regarding if it is IO-bound. I actually expected it would be, 
but both the Python and the D-version consume 100% CPU while 
running, and just copying the file around only takes a few 
seconds (cf 15-20 sec in runtime for the two programs). There's 
bound to be some aggressive file caching going on, but I figure 
that would rather normalize program runtimes at lower times 
after running them a few times, but I see nothing indicating 
that.


Two things that you could try:

First hitlists.byKey can be expensive (especially if hitlists is 
big). Instead use:


foreach( key, value ; hitlists )

Also the filter.array.length is quite expensive. You could use 
count instead.

import std.algorithm : count;
value.count!(h => h.pid >= (max_pid - max_pid_diff));



Re: Speeding up text file parser (BLAST tabular format)

2015-09-14 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Monday, 14 September 2015 at 12:30:21 UTC, Fredrik Boulund 
wrote:

Hi,

Using a small test file (~550 MB) on my machine (2x Xeon(R) CPU 
E5-2670 with RAID6 SAS disks and 192GB of RAM), the D version 
runs in about 20 seconds and the Python version less than 16 
seconds. I've repeated runs at least thrice when testing. This 
holds true even if the D version is compiled with -O.




Sounds like this program is actually IO bound. In that case I 
would not expect a really expect an improvement by using D. What 
is the CPU usage like when you run this program?


Also which dmd version are you using. I think there were some 
performance improvements for file reading in the latest version 
(2.068)


Re: Speeding up text file parser (BLAST tabular format)

2015-09-14 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Monday, 14 September 2015 at 14:54:34 UTC, Fredrik Boulund 
wrote:

On Monday, 14 September 2015 at 14:40:29 UTC, H. S. Teoh wrote:
I agree with you on that. I used Python's cProfile module to 
find the performance bottleneck in the Python version I posted, 
and shaved off 8-10 seconds of runtime on an extraneous 
str.split() I had missed.
I tried using the built-in profiler in DMD on the D program but 
to no avail. I couldn't really make any sense of the output 
other than that were enormous amounts of calls to lots of 
functions I couldn't find a way to remove from the code. Here's 
a paste of the trace output from the version I posted in the 
original post: http://dpaste.com/1AXPK9P




See this link for clarification on what the columns/numbers in 
the profile file mean

http://forum.dlang.org/post/f9gjmo$2gce$1...@digitalmars.com

It is still difficult to parse though. I myself often use sysprof 
(only available on linux), which automatically ranks by time 
spent.




Re: What is "FilterResult" type?

2015-09-08 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Tuesday, 8 September 2015 at 11:08:59 UTC, Bahman Movaqar 
wrote:

On Tuesday, 8 September 2015 at 10:08:03 UTC, cym13 wrote:
Filter is a template and returns a FilterResult range which is 
used to lazily compute the result. This behaviour is the same 
for map and the majority of functions in std.algorithm.


You can also use .array to (greedily) evaluate the results, which 
(for filter) will return a range of the same type as went in:


void main()
{
import std.array : array;
int[] arr = [1, 2, 3, 4, 5];
int[] result = arr.filter!(x => x%2).array;
}


Re: reading file byLine

2015-09-04 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Friday, 4 September 2015 at 12:06:08 UTC, Edwin van Leeuwen 
wrote:

On Friday, 4 September 2015 at 11:50:23 UTC, deed wrote:


import std.algorithm, std.range, std.array, std.string, 
std.stdio,

std.conv;

int[] arr1 = [1, 2, 30];
//arr1.max.writeln; // Doesn't work, as you say
arr1.reduce!max.writeln;// This does. Prints 30.


Again using reduce is the functional way to do it. The above 
basically boils down to:


int[] arr1 = [1, 2, 30];
int maxElement = arr1[1];
foreach( element; arr1[2..$] ) //2..$ is short hand for second 
till last ($) element

{
  maxElement = max( maxElement, element );
}
writeln( maxElement );


Sorry been using too much R, so my indexes are off by 1:

int[] arr1 = [1, 2, 30];
int maxElement = arr1[0];
foreach( element; arr1[1..$] ) //1..$ is short hand for second 
till last ($) element

{
  maxElement = max( maxElement, element );
}
writeln( maxElement );



Re: reading file byLine

2015-09-04 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 4 September 2015 at 11:50:23 UTC, deed wrote:


import std.algorithm, std.range, std.array, std.string, 
std.stdio,

std.conv;

int[] arr1 = [1, 2, 30];
//arr1.max.writeln; // Doesn't work, as you say
arr1.reduce!max.writeln;// This does. Prints 30.


Again using reduce is the functional way to do it. The above 
basically boils down to:


int[] arr1 = [1, 2, 30];
int maxElement = arr1[1];
foreach( element; arr1[2..$] ) //2..$ is short hand for second 
till last ($) element

{
  maxElement = max( maxElement, element );
}
writeln( maxElement );



Re: (De)Serializing interfaces

2015-08-24 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Monday, 24 August 2015 at 09:26:40 UTC, Edwin van Leeuwen 
wrote:

On Saturday, 22 August 2015 at 19:14:16 UTC, nims wrote:

Painlessjson indeed does not support interfaces/subclasses at 
the moment. There was some discussion about it here: 
https://github.com/BlackEdder/painlessjson/issues/8 , but we 
haven't really thought of a good way of doing it yet.




Pull requests are welcome of course :)



Re: (De)Serializing interfaces

2015-08-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Saturday, 22 August 2015 at 19:14:16 UTC, nims wrote:
I think interfaces are very powerful and I heavily use them. 
The only problem I have with them is that 
serializing/deserializing them to XML or JSON doesn't seem to 
work. So far I got to try Orange and painlessjson. Using Orange 
all I got was a lot of compiler errors. Painlessjson did 
compile normally but just ignores all interface class members.




Painlessjson indeed does not support interfaces/subclasses at the 
moment. There was some discussion about it here: 
https://github.com/BlackEdder/painlessjson/issues/8 , but we 
haven't really thought of a good way of doing it yet.


There is also:
http://code.dlang.org/packages/jsonizer
which I think should support at least subclasses, not sure about 
intefaces.


Re: Compiletime Vs Runtime bencmarks

2015-08-17 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 17 August 2015 at 14:43:35 UTC, D_Learner wrote:
Hello everyone . I need advice on my first D-project . I have 
uploaded it at :-


Current Results  for the pattern=GCAGAGAG  are as below :-

BM_Runtime  = 366 hnsecs position=   513
BM_Compile-time = 294 hnsecs position   =513

BMH_Runtime = 174 hnsecs position=   513
BMH_Compile-time= 261 hnsecs position=   513

AG_Run-time = 258 hnsecsposition=   513
AG_Compile-time = 268 hnsecsposition=   513


Running the code : dmd -J.  matcher.d inputs.d  rtime_pre.d 
ctime_pre.d  numactl --physcpubind=0 ./matcher




Hi,

What happens if you run each algorithm many (say 10) times. 
The current times seem to short to be reliable (variation in 
runtimes would be too great).


Regards, Edwin


Re: dub and subpackages

2015-08-14 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Friday, 14 August 2015 at 08:06:15 UTC, yawniek wrote:
i'm trying to have my own versions of my dependencies as git 
submodules.



whats the correct way of having a chain of packages included 
from git submodules so that every packages get's only picked 
once?


dub add-local allows you to add local copy of a package. This 
will be system wide though, not only for the current package.


Re: Indivisual Incremental Compalation with dub

2015-08-13 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 13 August 2015 at 05:42:38 UTC, Freddy wrote:
I have a file that takes a while to compile with a static 
interface. Is there any way i can make dub keep the object file 
of only that file(for faster compilation)?


I don't think dub itself can do this, but 
https://github.com/atilaneves/reggae should be able to do it. And 
it will parse/understand your dub configuration file.


Using return type of a predicate function as a template

2014-10-16 Thread Edwin van Leeuwen via Digitalmars-d-learn
I am trying to implement a groupBy function that groups by the 
return type of a predicate. Currently I have to define the 
returntype of the predicate for it to compile. Is there a way to 
get the return type at compile time and use it.


The code:
V[K] groupBy( alias func, K, V )( V values )
{
  V[K] grouped;
  foreach ( value ; values ) {
grouped[func( value )] ~= value;
  }
  return grouped;
}

unittest {
  struct Test {
string a;
double b;
  }

  auto values = [Test( a, 1 ), Test( a, 2 ), Test( b, 3 )];
  auto grouped = values.groupBy!( (a) = a.a, string );
  assert( grouped[a].length == 2 );
  assert( grouped[a][1].b == 2 );
  assert( grouped[b].length == 1 );
  assert( grouped[b][0].b == 3 );
}

So the above works, but I need to call it with:
values.groupBy!( (a) = a.a, string );
Ideally I would call it instead with:
values.groupBy!( (a) = a.a )
and it would infer that the template K needs to be a string, 
since that is the return type of (a) = a.a.


Cheers,

Edwin


Re: Using return type of a predicate function as a template

2014-10-16 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 16 October 2014 at 08:18:02 UTC, Atila Neves wrote:

This works:

import std.range;

auto groupBy(alias func, R)(R values)
if (isInputRange!R)
{

alias K = typeof(func(values.front));
alias V = ElementType!R[];
V[K] grouped;
foreach(value; values) grouped[func(value)] ~= value;
return grouped;
}



Thank you, that is surprisingly straightforward :)

Edwin


Re: Recomended cairo bindings

2014-09-15 Thread Edwin van Leeuwen via Digitalmars-d-learn
On Monday, 15 September 2014 at 12:11:09 UTC, Paul Z. Barsan 
wrote:
On Sunday, 14 September 2014 at 14:37:05 UTC, Robert burner 
Schadek wrote:


If you look at deimos.cairo you will see that the latest commit 
was made 2 years ago while cairoD was last updated 6 months ago.


I think the latest commit was made when I submitted a bug report. 
It seems that there is no ongoing development, but the 
maintainer/developer did react to my bug report very quickly, so 
it is/was still maintained at that time.


I made my choice: I will stick to dub, fork cairoD, merge 
everything from deimos.cairo into cairoDs C-style bindings  
wrappers, update cairoDs dependencies to use dub pkgs and then 
provide and rdmd script to configure platform specific stuff. I 
have plenty of time and if I succed, everyone can benefit from 
my work. :)


Out of curiosity: What does deimos.cairo add to cairoD? More 
higher level/d-like API?


Cheers, Edwin



Re: DUB: link to local library

2014-09-10 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Wednesday, 10 September 2014 at 13:40:16 UTC, rcor wrote:

dub.json contains what I think should do the same as above:
{
  name: test,
  importPaths: [ext/dallegro5],
  lflags: [-Lext/dallegro5]
}


Does adding:

libs: [dallegro5]

make a difference?

Cheers, Edwin


Re: D JSON (WAT?!)

2014-07-24 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Thursday, 24 July 2014 at 15:42:58 UTC, Pavel wrote:

On Thursday, 24 July 2014 at 15:38:06 UTC, John Colvin wrote:

On Thursday, 24 July 2014 at 15:32:29 UTC, John Colvin wrote:

On Thursday, 24 July 2014 at 15:15:37 UTC, Pavel wrote:

Ok, let me start with the sample code:

import std.stdio;
import std.json;

void main() {
scope(failure) writeln(FaILED!!);
string jsonStr = `{ name: 1, type: r }`;
auto parsed = parseJSON(jsonStr);
string s = parsed[fail].str;
writeln(s == );
writeln(s is null);
writeln(s);
}

Running rdmd app.d doesn't produce any output.
Can anyone explain such a behavior???


PS: Running dmd v2.065 on Linux x64.


It's a bug in std.json (you should get a segfault, not no 
output at all)


It is fixed now and I'm pretty sure it will be in 2.066

std.json has been improved a lot, but I would still recommend 
using http://vibed.org/api/vibe.data.json/ instead


perhaps bug is too strong a word, but it was a deficiency 
that is now corrected. You will get an exception thrown now 
and everything should work how you expect.


Maybe. But still it's not the way I expect, any time you check 
for non-existing property you must consider exception, which is 
very heavy to deal with in such a situation. I'd rather expect 
to get null, whenever I try to fetch non-existing property, and 
not an exception.


You can turn your json object into an AA object and then use in 
to check for existence (I know it is not very intuitive):


JSONValue[string] jsonAA = parsed.object;
if ( fail in jsonAA )
  s = jsonAA[fail].str;





That's purely my point, and I don't claim to be right in this 
way. It's up to Phobos maintainers to decide how to reprent 
JSON parsing results.




Re: Delegate, scope and associative array

2014-06-03 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 3 June 2014 at 05:40:44 UTC, Edwin van Leeuwen wrote:

On Monday, 2 June 2014 at 23:44:01 UTC, Rene Zwanenburg wrote:
On Monday, 2 June 2014 at 20:09:12 UTC, Edwin van Leeuwen 
wrote:
As you may have guessed, a workaround is to copy the iteration 
variable yourself:


unittest {
   size_t delegate()[size_t] events;
   foreach(_i; 1..4 ) {
   auto i = _i;
   events[i] = { return i; };
   }
   assert( events[1]() == 1 );
}

This should work though it's less than ideal. There is an open 
bug report:

https://issues.dlang.org/show_bug.cgi?id=8621


Thanks for the suggestion and I just tried it, but it does not
work :(

In the original code were I discovered this problem I generated
the id with an outside function and that also didn't to work.


unittest {
size_t delegate()[size_t] events;
size_t i = 1;
events[i] = { return i; };
i = 2;
events[i] = { return i; };
i = 3;
events[i] = { return i; };
writeln( events[1]() );
assert( events[1]() == 1 );
}

Explicitly removing the loop still causes the same issue. In that 
case I find it easier to understand, since it might be using the 
value of i at the end of the scope. In the foreach case (and 
especially when copying to a local variable) it is more puzzling 
to me.


Re: Delegate, scope and associative array

2014-06-03 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Tuesday, 3 June 2014 at 07:00:35 UTC, Ali Çehreli wrote:

Here is a workaround:

unittest {
size_t delegate()[size_t] events;

auto makeClosure(size_t i) {
return { return i; };
}

foreach( i; 1..4 ) {
events[i] = makeClosure(i);
}

assert( events[1]() == 1 );
}

void main()
{}

Ali


Thank you Ali, that works beautifully and can be easily adapted 
to the original (more complicated) case.


Cheers, Edwin


Delegate, scope and associative array

2014-06-02 Thread Edwin van Leeuwen via Digitalmars-d-learn
I'm probably missing something basic, but I am confused by what 
is going on in the following code.


unittest {
size_t delegate()[size_t] events;
foreach( i; 1..4 ) {
events[i] = { return i; };
}
writeln( events[1]() ); // This outputs 3
assert( events[1]() == 1 );
}

I thought that i should be copied from the local scope and 
therefore when I call events[1]() the return value should be 1, 
but in this case it is 3 (it always seems to be the last value of 
i in the loop).


Cheers, Edwin




Re: Delegate, scope and associative array

2014-06-02 Thread Edwin van Leeuwen via Digitalmars-d-learn

On Monday, 2 June 2014 at 23:44:01 UTC, Rene Zwanenburg wrote:

On Monday, 2 June 2014 at 20:09:12 UTC, Edwin van Leeuwen wrote:
As you may have guessed, a workaround is to copy the iteration 
variable yourself:


unittest {
size_t delegate()[size_t] events;
foreach(_i; 1..4 ) {
auto i = _i;
events[i] = { return i; };
}
assert( events[1]() == 1 );
}

This should work though it's less than ideal. There is an open 
bug report:

https://issues.dlang.org/show_bug.cgi?id=8621


Thanks for the suggestion and I just tried it, but it does not
work :(

In the original code were I discovered this problem I generated
the id with an outside function and that also didn't to work.