Re: debug mixins

2017-03-14 Thread Stefan Koch via Digitalmars-d-learn

On Wednesday, 15 March 2017 at 03:43:20 UTC, Inquie wrote:

So, is it possible to debug string mixins?

I ran visual D and tried to step in to a function that was 
generated by a mixin and it brought an open file dialog box 
asking me to load the source code where the function was 
located... of course, it wasn't located anywhere except in the 
mixin string.



This leads to the idea, why can't the compiler simply output 
the mixin string to a file then the debugger can load that 
source file?


One of the most frustrating things about D is not having the 
ability to debug it's powerful meta programming in any 
reasonable way. (bad enough having to resort to using 
pragma(msg))


But we can't even debug the results of those meta programming 
in the case of string mixins because there is no way to step in 
to them... It seems all the machinery is there, but just a few 
extra steps are needed.


In dmd ~master. there is an undocumented switch called -vcg-ast.
It will produce a file with everything expanded.
(Only if the code compiles with no errors).
It produces a cg-file which may or may not contain a valid source 
representation of the actual code compiled.


Re: debug mixins

2017-03-14 Thread Jonathan M Davis via Digitalmars-d-learn
On Wednesday, March 15, 2017 03:43:20 Inquie via Digitalmars-d-learn wrote:
> So, is it possible to debug string mixins?
>
> I ran visual D and tried to step in to a function that was
> generated by a mixin and it brought an open file dialog box
> asking me to load the source code where the function was
> located... of course, it wasn't located anywhere except in the
> mixin string.
>
>
> This leads to the idea, why can't the compiler simply output the
> mixin string to a file then the debugger can load that source
> file?
>
> One of the most frustrating things about D is not having the
> ability to debug it's powerful meta programming in any reasonable
> way. (bad enough having to resort to using pragma(msg))
>
> But we can't even debug the results of those meta programming in
> the case of string mixins because there is no way to step in to
> them... It seems all the machinery is there, but just a few extra
> steps are needed.

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

- Jonathan M Davis



debug mixins

2017-03-14 Thread Inquie via Digitalmars-d-learn

So, is it possible to debug string mixins?

I ran visual D and tried to step in to a function that was 
generated by a mixin and it brought an open file dialog box 
asking me to load the source code where the function was 
located... of course, it wasn't located anywhere except in the 
mixin string.



This leads to the idea, why can't the compiler simply output the 
mixin string to a file then the debugger can load that source 
file?


One of the most frustrating things about D is not having the 
ability to debug it's powerful meta programming in any reasonable 
way. (bad enough having to resort to using pragma(msg))


But we can't even debug the results of those meta programming in 
the case of string mixins because there is no way to step in to 
them... It seems all the machinery is there, but just a few extra 
steps are needed.






Re: strange CFTE issue

2017-03-14 Thread ag0aep6g via Digitalmars-d-learn

On 03/15/2017 03:01 AM, Inquie wrote:


If I do something like

enum X = Methods!(C);

foreach(x; X)
{
mixin(x);
}

I get an error about x not being a compile time variable. (code above is
simplified, the error has nothing to do with the form but of the
foreach(x )


"Compile time variable" may be misleading here. The compiler does not 
try to figure out what values are actually constant at compile time. 
Rather, the language defines some specific cases where it's guaranteed 
that a value is a compile-time constant. Only then can you use it in 
static contexts such as mixins. Other values are rejected, even if they 
would turn out be constant on a closer look.


`foreach` is mostly a run-time feature. There is a special case when you 
iterate over a "compile-time list" [1] (aka AliasSeq, formerly 
TypeTuple). In that case, the loop variable is recognized as a constant. 
That variant of `foreach` is also dubbed a "static foreach" (even though 
the `static` keyword is not used).


Note that it's not a "static foreach" when you iterate over an array, no 
matter if that array is constant at compile time or not.


So this works:

import std.meta: AliasSeq;
foreach (x; AliasSeq!("int foo;", "double bar;")) mixin(x);

But this doesn't:

foreach (x; ["int foo;", "double bar;"]) mixin(x);

This is expected and works as intended. Without the definition of your 
`Methods` template, I can't say for sure if you're hitting this or if 
something else is going on. But if your `X` is an array, this is it.



but if I wrap it in a function it works

string foo()
{
enum X = Methods!(C);
string y = "";
foreach(x; X)
{
   y ~= x;
}
 return y;
}

mixin(y);


(I'm assuming that last line should be `mixin(foo());`.)

The return value of `foo` is recognized as a compile-time constant 
there, because you call it in a context that forces it. This is called CTFE.


Note that you cannot assign the result of `foo()` to a variable first:

   string y = foo(); /* no CTFE */
   mixin(y); /* no go */

That's because `y` is a normal variable, which is not a recognized 
compile-time constant. The value could of course be evaluated at 
compile-time, but the compiler doesn't attempt CTFE opportunistically.



The only diff, of course, is the foreach in the first case mixes in on
each iteration, while in the second it doesn't... but it shouldn't
matter. in both cases x is the same.. and it definitely is a compile
time constant in both.


To the compiler it's not a "compile-time constant" in either of them (in 
a rather specific sense of the term "compile-time"). During CTFE, 
run-time rules apply. So in `foo`, `x` is a normal variable. The same 
rules apply as for actual run-time variables. Only the return value of 
`foo` is seen as a compile-time value by the compiler.


You're not the first one who stumbles over this meaning of "compile 
time". CTFE happens at compile time, and has "compile time" in the name, 
but during CTFE you're actually dealing with "run time" values that 
might never see the actual run time. Maybe these things could use some 
better names.



[1] https://dlang.org/ctarguments.html


Re: Declaring interfaces with a constructor

2017-03-14 Thread evilrat via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 13:54:41 UTC, David  Zhang wrote:


Yeah, that's the idea. Though I just thought of a possibility 
using an isPublicInterface template. Is that what you meant by 
templates and duck typing?


Not sure about what that template does, but the idea behind 
ranges is relying on duck-typing, that means if a provided 
type(usually a struct in case of ranges) provides some functions 
with specific signatures we can recognize it is a range. This 
isn't specifc to just ranges, but a common concept and one of the 
most widely known use case of it in D is ranges.


Now what i mean is that you just declare interface as contract, 
implement it for platform specific classes and rely on 
assumption(yeah, it seems like a bad idea) that your specific 
realization has specific ctors(well, it won't compile if it 
doesn't, so no big deal), so you also avoid pitfall of (lack of) 
multiple inheritance like with base abstract class.


with code shown below as example you also want to do some 
compile-time checks[1] in your functions when doing work with 
classes implemented by users in case you are writing a library, 
so if something is missed users will see a nice error message 
telling them about what's missing.

-

interface SomeCommonStuff
{
string getName();
int getRandomNumber();
...
}


version(Windows)
{
alias SomeCommonStuff_Impl = WinSpecifics;
class WinSpecifics : SomeCommonStuff // can also subclass any 
class

{
  this(int) {...}// shared interface ctor 1
  this(string) {...} // shared interface ctor 2

  // SomeCommonStuff implementation
  string getName() { return "win"; }
  int getRandomNumber() {return 42; }
  ...
}


version(linux)
{
alias SomeCommonStuff_Impl = LinuxSpecifics;
class LinuxSpecifics : SomeCommonStuff // can also subclass any 
class

{
  @disable this();   // disallow default ctor on linux
  this(int) {...}// shared interface ctor 1
  this(string) {...} // shared interface ctor 2

  // SomeCommonStuff implementation
  string getName() { return "linux"; }
  int getRandomNumber() {return 42; }
  ...
}

}

// your fail-safe for checking implementation has your specific 
ctor, see [1]
// you definitely do want some templates with it for easy checks 
for interface compliance
static assert(__traits(compiles, new SomeCommonStuff_Impl("string 
arg")));
static assert(!__traits(compiles, new 
SomeCommonStuff_Impl("string arg", "second string"))); // this 
will prevent compiling if you add ctor - this(string, string)


void main()
{
 auto platformClass = SomeCommonStuff_Impl("test");
 auto platformClass1 = SomeCommonStuff_Impl(42);

 // auto platformClass2 = SomeCommonStuff_Impl(); // will not 
compile on linux because default ctor disabled, but will work 
anywhere else

}



Another similar option is to use so-called Voldemort types, a 
type that cannot be named. You simply declare private platform 
specific class in your factory method body to make self-contained 
unit that returns new instance of that internal class, it can be 
used as a normal class instance anywhere but cannot be 
instantiated from outside (since type cannot be named)


Well, D offers quite a lot of flexibility, now i happy to give 
more insight on what can be done, but i've been out of D for 
quite a long time.




[1] https://dlang.org/spec/traits.html#compiles



Re: Function Template Overloading

2017-03-14 Thread Q. Schroll via Digitalmars-d-learn

On Wednesday, 15 March 2017 at 02:33:36 UTC, ketmar wrote:

Q. Schroll wrote:


void test(T)(T* arg);
void test(T)(ref T arg);

Let p be any pointer. Why is test(p) not an ambiguity error? 
Why is the second overload chosen?


'cause `ref T` is more generic than `T*`. think of it as 
"greedy matching": compiler first tries to match `int*`, and if 
that failed, it tries `int`, for example. and `int*` matches 
the second template, so compiler choosing it.


Wouldn't it be better vice versa, the more specific pattern to be 
prioritized? And as it actually *can* match both, is it a 
compiler-bug not to be an ambiguity error?


Re: Function Template Overloading

2017-03-14 Thread ketmar via Digitalmars-d-learn

Q. Schroll wrote:


void test(T)(T* arg);
void test(T)(ref T arg);

Let p be any pointer. Why is test(p) not an ambiguity error? Why is the 
second overload chosen?


'cause `ref T` is more generic than `T*`. think of it as "greedy matching": 
compiler first tries to match `int*`, and if that failed, it tries `int`, 
for example. and `int*` matches the second template, so compiler choosing it.


Function Template Overloading

2017-03-14 Thread Q. Schroll via Digitalmars-d-learn

void test(T)(T* arg);
void test(T)(ref T arg);

Let p be any pointer. Why is test(p) not an ambiguity error? Why 
is the second overload chosen?
Making the first one take auto ref T* lets the compiler choose 
the first.
Making the second one non-ref lets the compiler give me an 
ambiguity error.


Template Functions are not mentioned in the spec, at least not on 
https://dlang.org/spec/function.html#function-overloading, but it 
suggests that ref should not make the decision if it can be bound 
to.


Re: MemberDefaults trait

2017-03-14 Thread Ali Çehreli via Digitalmars-d-learn

On 10/10/2016 04:50 PM, Ali Çehreli wrote:
> Could you please review the following template to see whether it makes
> sense. It produces an AliasSeq type consisting of the default values of
> the members of a struct. It should and does support members that are
> initialized with '= void'. I could not achieve this with std.traits or
> __traits.

Reviving this thread because I've realized that the template does not 
work for members that are structs themselves.


/** Get as an expression tuple the default values of members of a struct. */
template MemberDefaults(T) {
static assert (is(T == struct), T.stringof ~ " is not a struct type");

import std.traits : FieldNameTuple;
enum t = T.init;
alias fields = FieldNameTuple!T;

template get(size_t i) {
static if (__traits(compiles, { enum get = t.tupleof[i]; })) {
enum get = t.tupleof[i];
}
else {
alias get = void;
}
}

template Impl(size_t i = 0) {
import std.meta : AliasSeq;
static if (i == fields.length) {
alias Impl = AliasSeq!();
} else {
alias Impl = AliasSeq!(get!i, Impl!(i+1));
}
}

alias MemberDefaults = Impl!();
}

struct Foo {
string s;
int i;
}

unittest {
struct S {
int i = 42;
string s = "hello";
char c = 'c';
int j = void;
Foo foo0;
Foo fooVoid = void;
}

alias result = MemberDefaults!S;

import std.meta : AliasSeq;
if (!is(result == AliasSeq!(42, "hello", 'c', void, Foo, void))) {
pragma(msg, "Did not match: ", result);
static assert(false);
}
}

void main() {
}

Here is the output of a -unittest compilation:

  Did not match: tuple(42, "hello", 'c', (void), Foo(null, 0), Foo(, ))

Notice how the j member worked as expected: Its default value appeared 
as (void) in the result. (Aside: It's strange that pragma(msg) 
parenthesizes it.)


The problem is, the default value of the fooVoid member does not appear 
as void but as "Foo(, )". This seems to be a compiler bug to me. One 
might parse that string as a workaround but then it wouldn't work for 
empty structs. (Although, empty structs could be excluded by this 
template. Hmmm... That might work.)


Can you make this work? i.e. Can you make the result be

  AliasSeq!(42, "hello", 'c', void, Foo, void)

Is it possible to detect members that are void-initialized at all?

Ali



strange CFTE issue

2017-03-14 Thread Inquie via Digitalmars-d-learn


If I do something like

enum X = Methods!(C);

foreach(x; X)
{
mixin(x);
}

I get an error about x not being a compile time variable. (code 
above is simplified, the error has nothing to do with the form 
but of the foreach(x )


but if I wrap it in a function it works

string foo()
{
enum X = Methods!(C);
string y = "";
foreach(x; X)
{
   y ~= x;
}
 return y;
}

mixin(y);

The only diff, of course, is the foreach in the first case mixes 
in on each iteration, while in the second it doesn't... but it 
shouldn't matter. in both cases x is the same.. and it definitely 
is a compile time constant in both. (Methods is just a wrapper on 
__traits(allMembers) but does some manipulation (stole the code 
from somewhere on the forum))





Acruvex dll in D

2017-03-14 Thread Cassio Butrico via Digitalmars-d-learn
I have this activex dll in vb6 and would like to be able to use 
it in D


CClasexp.cls

Public Function Add (X As Integer, and As Integer)
 Add = (X + y)
End Function

How do i instantiate activex dll in D?



Re: code folding

2017-03-14 Thread Ali Çehreli via Digitalmars-d-learn

On 03/14/2017 02:48 PM, Inquie wrote:

>> version (all) {
>> // ...
>> }
>>
>> You can define your own version identifiers as well:
>>
>> version = some_descriptive_name;
>>
>> version (some_descriptive_name) {
>> // ...
>> }
>>
>> Ali
>
> Oh, that might be better. I thought of versions but I didn't want to
> have to define anything... didn't know about all.

I remembered reading about it here: ;)

  http://ddili.org/ders/d.en/cond_comp.html#ix_cond_comp.all,%20version

which includes a link to the very long list of pre-defined version 
identifiers here:


  http://dlang.org/spec/version.html#predefined-versions

Ali



Re: code folding

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 20:56:02 UTC, Ali Çehreli wrote:

On 03/13/2017 10:29 AM, Inquie wrote:
Does D have any nice way to specify a block for cold folding? 
I have a
very large set of structs and I'd like to be able to code fold 
them all

at once and together.

I have been using

static if(true)
{
... junk
}

but the static if is uninformative since that is the only line 
that is

shown when folded. A comment helps but still kinda ugly.

C# has #regions and hopefully D has something as useful.



There is version:

version (all) {
// ...
}

You can define your own version identifiers as well:

version = some_descriptive_name;

version (some_descriptive_name) {
// ...
}

Ali


Oh, that might be better. I thought of versions but I didn't want 
to have to define anything... didn't know about all.





Re: Phobos function to check if files are identical?

2017-03-14 Thread XavierAP via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 18:26:52 UTC, flamencofantasy wrote:


  import std.mmfile;

  auto f1 = new MmFile("file1");
  auto f2 = new MmFile("file2");

  return f1[] == f2[];


Nice! I don't have experience with memory-mapped files. What are 
the pros and cons?


Re: code folding

2017-03-14 Thread Ali Çehreli via Digitalmars-d-learn

On 03/13/2017 10:29 AM, Inquie wrote:

Does D have any nice way to specify a block for cold folding? I have a
very large set of structs and I'd like to be able to code fold them all
at once and together.

I have been using

static if(true)
{
... junk
}

but the static if is uninformative since that is the only line that is
shown when folded. A comment helps but still kinda ugly.

C# has #regions and hopefully D has something as useful.



There is version:

version (all) {
// ...
}

You can define your own version identifiers as well:

version = some_descriptive_name;

version (some_descriptive_name) {
// ...
}

Ali



Re: Filter out common object functions

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 19:43:59 UTC, Adam D. Ruppe wrote:

On Tuesday, 14 March 2017 at 19:39:26 UTC, Inquie wrote:

__traits(allMembers, T);


Try derivedMembers instead.


That doesn't work, unfortunately, probably because of the types 
I'm using(just returns object.


What I can do is this:

	enum isElementOfObject(alias T) = (staticIndexOf!(T, 
__traits(allMembers, Object)) < 0) ? true : false;
	enum isElementOfIDispatch(alias T) = (staticIndexOf!(T, 
__traits(allMembers, IDispatch)) < 0) ? true : false;	
	enum membersList = Filter!(isElementOfIDispatch, 
Filter!(isElementOfObject, __traits(derivedMembers, T)));



It would be nice if instead of having to make a large list of 
isElementOf, I could pass the types to the predicate:



enum isElementOf(alias S, alias T) = (staticIndexOf!(T, 
__traits(allMembers, S)) < 0) ? true : false;
	enum membersList = Filter!(isElementOf!Object, 
__traits(derivedMembers, T)));


and ultimately give a list of objects:


	enum membersList = Filter!(isElementOf!(Object, IDispatch), 
__traits(derivedMembers, T)));



Would be pretty cool if D could do that, but I doubt it can ;/ 
(not logically impossible, sort of like currying or something)


Re: Filter out common object functions

2017-03-14 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 19:39:26 UTC, Inquie wrote:

__traits(allMembers, T);


Try derivedMembers instead.


Filter out common object functions

2017-03-14 Thread Inquie via Digitalmars-d-learn
I am iterating over the members of classes and interfaces and get 
things like hash, this, etc. These are causing problems in my 
code. I would like to get only the "specified" members.


While I can filter out

__traits(allMembers, T);

using Erase, it is tedius and error prone.

Is there a way to get only the immediate members? Non-inherited, 
and "common"(for a lack of a better word), this(), for example, 
is specified by the language... i don't need it, just functions 
the user specifies in the type.




Re: Function pointer pitfalls

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 19:14:34 UTC, H. S. Teoh wrote:
On Tue, Mar 14, 2017 at 06:59:58PM +, Inquie via 
Digitalmars-d-learn wrote:

[...]

[...]

> [...]

[...]

[...]

[...]

Keep in mind, though, that the above creates a function pointer 
with the same signature as the member function, but you may not 
be able to assign a member pointer to it because it lacks 
object context.  To wit:


[...]


Yeah, I don't think I'll run in to that problem since I'm 
constructing the function ahead of time and only need the 
declaration but we'll see.


Thanks again.




Re: Function pointer pitfalls

2017-03-14 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Mar 14, 2017 at 06:59:58PM +, Inquie via Digitalmars-d-learn wrote:
> On Tuesday, 14 March 2017 at 17:42:34 UTC, H. S. Teoh wrote:
[...]
> > struct X {
> > int method(float x) { return 0; }
> > }
> > 
> > typeof() membptr;
> > pragma(msg, typeof(membptr)); // prints `int function(float x)`
> > 
> > If you need to refer to the function pointer type frequently, you
> > could alias it to something easier to type;
> > 
> > alias FuncPtr = typeof();
> > FuncPtr membptr;
[...]
> Thanks, that will work. In C++ there were issues with pointers and one
> would have to properly group the function name or some thing like
> that. Your suggestion avoids all that.
[...]

Keep in mind, though, that the above creates a function pointer with the
same signature as the member function, but you may not be able to assign
a member pointer to it because it lacks object context.  To wit:


struct X {
int method(float x) { return 0; }
}

X x;

alias FuncPtr = typeof();
FuncPtr fp;

alias MembPtr = typeof();
MembPtr mp;

mp =  // OK
//fp =  // NG: cannot implicitly convert expression 
() of type int delegate(float z) to int function(float z)
-

 is a delegate because it encapsulates the instance of X that
it should be invoked with, so you can't assign it to a func ptr without
that context (since method() can't be called without an instance of X).


T

-- 
Question authority. Don't ask why, just do it.


Re: Function pointer pitfalls

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 17:42:34 UTC, H. S. Teoh wrote:
On Tue, Mar 14, 2017 at 05:05:10PM +, Inquie via 
Digitalmars-d-learn wrote:
I am generating member function pointers using the declaration 
specified from a standard member function. The standard member 
function is a valid D function that could use any types.


Is there any pitfalls like there are in C++ from generating a 
function pointer from them?


e.g.,

X foo(A,B,C) @R @S @T -> X function(A,B,C) @R @S @T fooptr;

In my case, there are no attributes, so that might ease the 
burden.


e.g., a template that converts a member function declaration.

ToFunctionPtr!("X foo(A,B,C) @R @S @T)", fooptr)

or

ToFunctionPtr!(foo, fooptr)

gives function pointer declaration who's declaration is the 
same as foo.


Not 100% sure what exactly you mean... but I'm guessing you 
have some aggregate X with some member function method(), and 
you want to get a function pointer from that? Perhaps something 
like this?


struct X {
int method(float x) { return 0; }
}

typeof() membptr;
pragma(msg, typeof(membptr)); // prints `int function(float x)`

If you need to refer to the function pointer type frequently, 
you could alias it to something easier to type;


alias FuncPtr = typeof();
FuncPtr membptr;


T


Thanks, that will work. In C++ there were issues with pointers 
and one would have to properly group the function name or some 
thing like that. Your suggestion avoids all that.





Re: Inline mixin

2017-03-14 Thread Daniel Kozak via Digitalmars-d-learn

Dne 14.3.2017 v 18:38 Inquie via Digitalmars-d-learn napsal(a):

Many times I need to build a type using a string. I have to resort to 
building the entire expression/statement using the mixin:


mixin("This is a long and complex expression where I only need to 
modify X")


Is there any way to do a sort of "inline mixin"?


This is a long and complex expression where I only need to modify 
mixin("X")


?

e.g.,

mixin("int "~name~" = 3;")

vs

int mixin(name) = 3;

(a gross simplification)



Maybe a template could handle it or is something like this impossible 
by D's gramar?



You can combine template and mixin.

something like this:

enum Z(alias X) = "int x = " ~ X.stringof ~ ";";

void main()
{
import std.stdio : writeln;
mixin(Z!1);
writeln(x);
}



Re: Phobos function to check if files are identical?

2017-03-14 Thread flamencofantasy via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 08:31:20 UTC, XavierAP wrote:

On Tuesday, 14 March 2017 at 08:12:16 UTC, Andrea Fontana wrote:


First I would check if the files have different size or if 
they are the same file (same path, symlink, etc).


Good idea. Good reason to have it in std.file. There might also 
be platform dependent shortcuts?



  import std.mmfile;

  auto f1 = new MmFile("file1");
  auto f2 = new MmFile("file2");

  return f1[] == f2[];



Re: Function pointer pitfalls

2017-03-14 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Mar 14, 2017 at 05:05:10PM +, Inquie via Digitalmars-d-learn wrote:
> I am generating member function pointers using the declaration
> specified from a standard member function. The standard member
> function is a valid D function that could use any types.
> 
> Is there any pitfalls like there are in C++ from generating a function
> pointer from them?
> 
> e.g.,
> 
> X foo(A,B,C) @R @S @T -> X function(A,B,C) @R @S @T fooptr;
> 
> In my case, there are no attributes, so that might ease the burden.
> 
> e.g., a template that converts a member function declaration.
> 
> ToFunctionPtr!("X foo(A,B,C) @R @S @T)", fooptr)
> 
> or
> 
> ToFunctionPtr!(foo, fooptr)
> 
> gives function pointer declaration who's declaration is the same as
> foo.

Not 100% sure what exactly you mean... but I'm guessing you have some
aggregate X with some member function method(), and you want to get a
function pointer from that? Perhaps something like this?

struct X {
int method(float x) { return 0; }
}

typeof() membptr;
pragma(msg, typeof(membptr)); // prints `int function(float x)`

If you need to refer to the function pointer type frequently, you could
alias it to something easier to type;

alias FuncPtr = typeof();
FuncPtr membptr;


T

-- 
Turning your clock 15 minutes ahead won't cure lateness---you're just making 
time go faster!


Inline mixin

2017-03-14 Thread Inquie via Digitalmars-d-learn
Many times I need to build a type using a string. I have to 
resort to building the entire expression/statement using the 
mixin:


mixin("This is a long and complex expression where I only need to 
modify X")


Is there any way to do a sort of "inline mixin"?


This is a long and complex expression where I only need to modify 
mixin("X")


?

e.g.,

mixin("int "~name~" = 3;")

vs

int mixin(name) = 3;

(a gross simplification)



Maybe a template could handle it or is something like this 
impossible by D's gramar?




Re: code folding

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 17:07:57 UTC, Adam D. Ruppe wrote:

On Monday, 13 March 2017 at 17:29:41 UTC, Inquie wrote:

Does D have any nice way to specify a block for cold folding?


I personally sometimes use

// some description {

// }

since my editor does a really good job matching {}, even in 
comments so it is convenient to jump anywhere, and i can search 
the description text to get back to it from anywhere.


I can fold it too but i personally prefer just jumping it than 
actually folding it.


Yeah, that would be better, unfortunately VS/VD doesn't do this.


Re: code folding

2017-03-14 Thread flamencofantasy via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 16:58:21 UTC, Inquie wrote:

On Tuesday, 14 March 2017 at 16:29:15 UTC, Mike Parker wrote:

[...]


It's not that I feel strongly about, I simply would like the 
best useable solution. Like usually what happens, my original 
post was taken completely out of context:


[...]


static if(true) // region blah
{
   junk...
}

when folded;

static if (true) // #region blah{...}

does that solve your problem?


Re: code folding

2017-03-14 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 13 March 2017 at 17:29:41 UTC, Inquie wrote:

Does D have any nice way to specify a block for cold folding?


I personally sometimes use

// some description {

// }

since my editor does a really good job matching {}, even in 
comments so it is convenient to jump anywhere, and i can search 
the description text to get back to it from anywhere.


I can fold it too but i personally prefer just jumping it than 
actually folding it.


Function pointer pitfalls

2017-03-14 Thread Inquie via Digitalmars-d-learn
I am generating member function pointers using the declaration 
specified from a standard member function. The standard member 
function is a valid D function that could use any types.


Is there any pitfalls like there are in C++ from generating a 
function pointer from them?


e.g.,

X foo(A,B,C) @R @S @T -> X function(A,B,C) @R @S @T fooptr;

In my case, there are no attributes, so that might ease the 
burden.


e.g., a template that converts a member function declaration.

ToFunctionPtr!("X foo(A,B,C) @R @S @T)", fooptr)

or

ToFunctionPtr!(foo, fooptr)

gives function pointer declaration who's declaration is the same 
as foo.




Re: groupBy in D?

2017-03-14 Thread Russel Winder via Digitalmars-d-learn
On Tue, 2017-03-14 at 16:35 +, Russel Winder wrote:
> 

So by analogy with the Python code I get the following D code, but it
seems ugly compared to the niceness of the Groovy code (and equivalent
Kotlin and Ceylon codes):

import std.array: array, split;
import std.algorithm: filter, map;
import std.file: dirEntries, SpanMode;
import std.path: baseName, dirName;
import std.stdio: writeln;
import std.typecons: Tuple, tuple;


auto files = dirEntries(path, SpanMode.shallow)
 .filter!(a => a.isFile)
 .map!(a => a.baseName)
 .map!(a => tuple(a.split('_')[0], a))
 .array;
writeln(files);
string[][string] groups;
foreach (Tuple!(string, string) f; files) {
groups[f[0]] ~= [f[1]];
}



-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

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


Re: code folding

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 16:29:15 UTC, Mike Parker wrote:

On Tuesday, 14 March 2017 at 15:44:27 UTC, Inquie wrote:



So, with all the bloviating, all I have arrived at is that my 
original hack is still the only way to get the cold folding I 
wanted(the original use case I had in mind, even though I'd 
rather have proper code structuring support in general). 
Generally when even a hint of a suggestion of a language 
addition is created, the worms come out to party...


If it's something you feel strongly about, then the way to go 
about it is to put together a DIP. There was a time when you 
could open a forum post about a new feature and eventually see 
it added, but those days are long gone (for good reason). If 
any new feature is going to have any hope of getting in these 
days, then it needs someone to champion it through the DIP 
process.


It's not that I feel strongly about, I simply would like the best 
useable solution. Like usually what happens, my original post was 
taken completely out of context:


"Does D have any nice way to specify a block for cold folding? I 
have a very large set of structs and I'd like to be able to code 
fold them all at once and together.


I have been using

static if(true)
{
... junk
}

but the static if is uninformative since that is the only line 
that is shown when folded. A comment helps but still kinda ugly.


C# has #regions and hopefully D has something as useful.
"

No where do I mention anything about a language change. I asked 
if D had something useful and better than my hack. What it seems 
to stir up is a bunch of people that have a fear based reaction, 
which I can only hypothesize why. Usually it involves someone 
trying to state absolutely why what I am doing is wrong or bad 
and all they offer is anecdotal evidence and their opinions. None 
of which are helpful or useful.


I would wager that more than 50% of D users have this mentality, 
and given that, it is highly unlikely that I could push for such 
changes. I'd get more done and have more use by forking D and 
adding my own features for my own personal use.


What perplexes me is why so many have such a disdain for any 
change that ultimately doesn't effect them much. If, say the 
"#regions" feature was implement, or some variant, and they are 
right and it is useless then chances of them ever encountering 
such code is slim... and code they do encounter would generally 
not a a problem(light use). Yet, those that do use it(in house), 
which, if it is so bad, according to them, should be rare, would 
benefit from it, at least in their own mind.


You know, there is something called "Survival of the fittest" and 
if an idea is truly bad then it will die out. Many people don't 
even want to give any idea a chance to go through that process... 
fear of it being successful? Fear they might have to learn 
something new? Fear it might require them to adapt their 
understanding of how things work? Fear of it being a waste of 
time? Fear of it causing a nuclear meltdown? When it will affect 
them almost nil, and they rail against it, it is some deep seeded 
fear from something... Unless they can give nearly absolute 
mathematical proof why it is invalid/wrong.


Anyways, my hack is good enough for me. If they ever see any of 
my code, they might rather have allowed something a bit more 
syntactically pleasing and so they can blame themselves(which 
they won't). Of course, we could always depreciate "static if 
(true)" to prevent that possibility! Maybe that is the real 
solution?













Re: Using chunks with Generator

2017-03-14 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Mar 14, 2017 at 12:30:13PM +, Era Scarecrow via Digitalmars-d-learn 
wrote:
> On Tuesday, 14 March 2017 at 10:00:24 UTC, Tetiana wrote:
> > Build fails with the following error:
> 
> Just looking at the Documentation, Generator is an InputRange and
> chunks requires a ForwardRange (able to use save functionality).
> 
>  So the API doesn't match up more or less.
> 
> https://dlang.org/phobos/std_concurrency.html#.Generator
> https://dlang.org/phobos/std_range.html#chunks

You probably need to cache the generated elements so that they can be
reused.

Or you could try using std.algorithm.iteration.chunkBy instead, which
*can* work with mere input ranges (that aren't necessarily forward
ranges).  Note, though, that you would only be able to evaluate each
element once, and calling popFront on the outer range will discard all
elements in the current chunk.  This is generally OK for single-pass
algorithms, but if you ever need to backtrack or process chunk elements
out-of-order, it won't work and you'll need to cache.


T

-- 
Help a man when he is in trouble and he will remember you when he is in trouble 
again.


Re: code folding

2017-03-14 Thread bachmeier via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 16:29:15 UTC, Mike Parker wrote:

If it's something you feel strongly about, then the way to go 
about it is to put together a DIP. There was a time when you 
could open a forum post about a new feature and eventually see 
it added, but those days are long gone (for good reason). If 
any new feature is going to have any hope of getting in these 
days, then it needs someone to champion it through the DIP 
process.


In addition, not that it won't get very far without a 
demonstration of how this (a) can't be done using comments, and 
(b) can't be handled at the IDE level. I have to admit that I do 
not understand at this point why a change to the language is 
needed.


On the other hand, if this does provide value, I'd expect it to 
be one of the easiest possible additions to push through, because 
it won't break anyone's code.


Re: groupBy in D?

2017-03-14 Thread Russel Winder via Digitalmars-d-learn
On Tue, 2017-03-14 at 16:12 +0100, Daniel Kozak via Digitalmars-d-learn 
wrote:
> […]
> 
> Can you post some example? Maybe in python, kotlin whatever so I can 
> better understand what you want

In my head I had something such as Groovy's

  files = new File('test-data').listFiles().collect{it.name}
  println files.groupBy({ it.split('_')[0]})


The I remembered that itertools.groupby in Python behaves like D's
std.algorithm.iteration.chunkBy and not like Groovy's groupBy. So in
Python you have to hack it with:

  from collections import defaultdict
  from os import listdir
  from os.path import isfile, splitext

  result = defaultdict(list)
  files = tuple((item.split('_')[0], item) for item in listdir('test-data') if 
isfile('test-data/' + item))
  for p, v in files:
result[p] += [v]
  print(result)

Given the seeming lack of Groovy-style groupBy, I guess I will have to
do something Python-like in D. Except I am not sure D has an equivalent
of defaultdict.

-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

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


Re: What is PostgreSQL driver is most stable?

2017-03-14 Thread Paolo Invernizzi via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 13:32:31 UTC, Suliman wrote:
On Tuesday, 14 March 2017 at 13:21:39 UTC, Paolo Invernizzi 
wrote:

On Tuesday, 14 March 2017 at 13:13:31 UTC, Suliman wrote:

[...]


I'm using ddb [1], a full-D implementation of the PostgreSQL 
protocol. Not everything it's in place, but it does its works, 
and the codebase is pretty simple, so it's not difficult to 
contribute if you need to add some feature that's missing for 
your use case.


[1] https://github.com/pszturmaj/ddb

---
Paolo


Does it work fine on Linux with x64 Postgres?


Yes

---
Paolo


Re: code folding

2017-03-14 Thread Mike Parker via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 15:44:27 UTC, Inquie wrote:



So, with all the bloviating, all I have arrived at is that my 
original hack is still the only way to get the cold folding I 
wanted(the original use case I had in mind, even though I'd 
rather have proper code structuring support in general). 
Generally when even a hint of a suggestion of a language 
addition is created, the worms come out to party...


If it's something you feel strongly about, then the way to go 
about it is to put together a DIP. There was a time when you 
could open a forum post about a new feature and eventually see it 
added, but those days are long gone (for good reason). If any new 
feature is going to have any hope of getting in these days, then 
it needs someone to champion it through the DIP process.


Re: code folding

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 15:18:00 UTC, bachmeier wrote:
On Tuesday, 14 March 2017 at 00:38:12 UTC, Vladimir Panteleev 
wrote:


FYI: The "you must implement my feature request or D will 
never succeed" attitude is rather common and never helpful. 
Not to mention that such an argument would be demonstrably 
false: every popular language without the feature you want has 
apparently succeeded despite not having said feature.


This is a little different, however, in the sense that there is 
no reason to add a feature to the language to do what is 
requested. If you use Emacs, you can get the same thing in any 
language using comments:


https://www.emacswiki.org/emacs/FoldingMode


and I agree that having an such a feature(for #region) would 
better be handled by comments(assuming it, itself, can be 
commented out easily). But either way, we do not have the 
capabilities with D in the first place. I do not use Emacs but 
the Visual D, which I assume is the sponsored IDE for D.



This is an issue for the IDE, not for the language, and 
changing the language would not have any effect on IDE support 
for code folding.


Remember, it is not just about code folding(which seems to be the 
common misconception). The cold folding is a sort of byproduct of 
struct defining language features... of which, D has very little 
of. Version, is a good one for certain things, but useless here 
for code structure itself.


My original statement was if D had the ability to do proper code 
folding rather than resorting to hacks and it has been derailed 
in to an language vs ide battle.


So, with all the bloviating, all I have arrived at is that my 
original hack is still the only way to get the cold folding I 
wanted(the original use case I had in mind, even though I'd 
rather have proper code structuring support in general). 
Generally when even a hint of a suggestion of a language addition 
is created, the worms come out to party...










Re: Can i using D & LLVM & SDL2 for Android?

2017-03-14 Thread Joakim via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 01:57:56 UTC, rikki cattermole wrote:

On 14/03/2017 6:08 AM, Joakim wrote:
On Monday, 13 March 2017 at 09:33:39 UTC, rikki cattermole 
wrote:

On 13/03/2017 7:48 PM, Joakim wrote:

[...]


Why exactly doesn't the Android port support dlopen, dlsym 
and dlclose?

It is provided by the NDK libc.

At least according to this[0].

[0] https://developer.android.com/ndk/guides/stable_apis.html


I was more talking about D shared libraries, which I'm assuming
DerelictSDL2 qualifies as and would require Phobos built as a 
shared

library.  That hasn't been tried yet on Android.


DerelictSDL2 would be statically linked, it would dynamically 
bind via dlopen, dlsym and dlclose to SDL itself which would be 
compiled as a shared library.


This is how Derelict based libraries work.


Ah, I have either misunderstood or forgotten how Derelict works.  
If the D code is all statically linked and only non-D, C/C++ 
shared libraries are loaded in addition to the single D shared 
library, there should be no problem using all Derelict modules on 
Android.


Re: code folding

2017-03-14 Thread bachmeier via Digitalmars-d-learn
On Tuesday, 14 March 2017 at 00:38:12 UTC, Vladimir Panteleev 
wrote:


FYI: The "you must implement my feature request or D will never 
succeed" attitude is rather common and never helpful. Not to 
mention that such an argument would be demonstrably false: 
every popular language without the feature you want has 
apparently succeeded despite not having said feature.


This is a little different, however, in the sense that there is 
no reason to add a feature to the language to do what is 
requested. If you use Emacs, you can get the same thing in any 
language using comments:


https://www.emacswiki.org/emacs/FoldingMode

This is an issue for the IDE, not for the language, and changing 
the language would not have any effect on IDE support for code 
folding.


Testing directory processing codes

2017-03-14 Thread Russel Winder via Digitalmars-d-learn
I am wondering how to test D functions that manipulate filestores.

In Python I'd wheel out pytest and create fixtures that use tempfile
module functions to create temporary directories and files. I'd also
try and use Hypothesis to do some property based testing using randomly
generated directories and files.

Moral of this story, I haven't done real D programming in quite a
while, and am having to re-learn stuff.

-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

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


Re: groupBy in D?

2017-03-14 Thread Daniel Kozak via Digitalmars-d-learn

Dne 14.3.2017 v 16:02 Russel Winder via Digitalmars-d-learn napsal(a):


I am having a hard time Google-ing today. Pytho, Groovy, Kotlin, etc.
have a "groupBy" function that takes a sequence and a key and creates a
dictionary/associative array with keys the result of the key function
on the sequence and key values all the items that match the key.

D doesn't seem to have such a function directly. Unless I missed it…
Can you post some example? Maybe in python, kotlin whatever so I can 
better understand what you want


Re: listdir

2017-03-14 Thread Daniel Kozak via Digitalmars-d-learn

There is no such function in D2

You can use dirEntries

https://dlang.org/phobos/std_file.html#.dirEntries.2


Dne 14.3.2017 v 16:04 hadas via Digitalmars-d-learn napsal(a):

Hi,
I'm trying to read all the txt files in specific path.
I tried to use listdir function, but I get this error:
Error: undefined identifier 'listdir' in module 'std.file'





import std.stdio;
import std.file;

void main(string[] args)
{

auto vm_files = std.file.listdir("C:/Users/hadas/Documents/d", "*.txt");

foreach(d;vm_files)
writeln(d);

}





listdir

2017-03-14 Thread hadas via Digitalmars-d-learn

Hi,
I'm trying to read all the txt files in specific path.
I tried to use listdir function, but I get this error:
Error: undefined identifier 'listdir' in module 'std.file'





import std.stdio;
import std.file;

void main(string[] args)
{

auto vm_files = std.file.listdir("C:/Users/hadas/Documents/d", 
"*.txt");


foreach(d;vm_files)
writeln(d);

}



groupBy in D?

2017-03-14 Thread Russel Winder via Digitalmars-d-learn
I am having a hard time Google-ing today. Pytho, Groovy, Kotlin, etc.
have a "groupBy" function that takes a sequence and a key and creates a
dictionary/associative array with keys the result of the key function
on the sequence and key values all the items that match the key.

D doesn't seem to have such a function directly. Unless I missed it…

-- 
Russel.
=
Dr Russel Winder  t: +44 20 7585 2200   voip: sip:russel.win...@ekiga.net
41 Buckmaster Roadm: +44 7770 465 077   xmpp: rus...@winder.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder

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


Re: code folding

2017-03-14 Thread Inquie via Digitalmars-d-learn

Just for fun:

1. Folding directives are glorified comments. #region has zero 
meaning to the compiler; it's a hint to the editor to allow code 
folding. It doesn't do any namespacing or scoping. Why, exactly, 
are we writing code to accommodate the editor? It boggles my mind 
that we'd add significant lines of code to our project that do 
nothing but offer organizational hints to the editor. Even 
traditional comments are a better value for your keystroke, 
because they can be more expressive. And folding is certainly no 
substitute at all for bona-fide refactoring.


BS. I use regions in C# to separate disparate code. I like to 
know how my code functions and the structure of code relative to 
itself. It helps conceptually understand the code better.


2. Folding is used to sweep code under the rug. Got a bunch of 
boring boilerplate code that makes your eyes water? A slew of 
ugly, gnarly code that nobody in their right mind wants to look 
at? Hide it in a region and fold that sucker into oblivion! 
Problem solved, right? Hardly. Your project is now full of crappy 
code that you can't see. That's worse. Much worse! Code that 
hides from you is code that will rot in the most putrescent and 
painful way possible. Your code should be front and center at all 
times -- exposed to as many programmers' eyes, and as much 
healing light, as possible.


No matter what color language you use to object to something 
doesn't mean it is more true. I guess this guy doesn't realize 
that you can unfold the code.


3. Folding is used to mask excessive length. The presence of 
folded code can lull developers into a false sense of what clean 
code looks like. Under the cover of folding, you can end up 
writing long, horrible spaghetti code blocks. If the code needs 
the crutch of folding to look organized, it's bad code.


Well duh, that is one of the benefits of it.

I'll state it again. I use regions in C# to separate disparate 
code. I like to know how my code functions and the structure of 
code relative to itself. It helps conceptually understand the 
code better.




4. Folding can hide deficiencies in your editor. The presence of 
so-called "standard" boilerplate regions like "Public 
Constructors" and "Public Properties" and "Events" is not a 
feature. It's a bug. The editor should automatically offer to 
fold up these common structural blocks for you! I'm continually 
amazed that programmers spend time doing this scutwork when they 
could be writing useful code. Or at least demanding a smarter 
code editor.


This guy obviously doesn't know what a bug is so how could we 
trust his "expertise"? But which is it? the language or the 
stupid IDE? I'm confused?



This guy probably never used #regions to learn how to use them 
properly and has such a pathetic uptight life that all he can do 
is bitch about other peoples poor code practices. That is no 
proof of anything. Instead of bitching, like most people, why 
didn't he write a constructive article about how to use #regions 
properly?


Anyone can write a blog these days kinda sad actually. ;/



I guess you will then state that he is an amazing programmer 
because of SO and that we should all bow down to his wisdom? 
yeah, right





Re: code folding

2017-03-14 Thread Inquie via Digitalmars-d-learn
On Tuesday, 14 March 2017 at 00:38:12 UTC, Vladimir Panteleev 
wrote:

On Monday, 13 March 2017 at 21:33:56 UTC, Inquie wrote:
One can say that it is a useless feature because D doesn't 
have it... or one could say that D is useless because it 
doesn't have it. A nice balance is simply to say "It is a 
useful feature that has proven it's worth and it is time that 
D implements something like it". As D becomes more mainstream, 
these features will be requested. D should learn from other 
language/compilers just as other languages/compilers have 
learned from it. (it's a two a way street)


FYI: The "you must implement my feature request or D will never 
succeed" attitude is rather common and never helpful. Not to 
mention that such an argument would be demonstrably false: 
every popular language without the feature you want has 
apparently succeeded despite not having said feature.




I never said that. I said those were the extremes and you decided 
to pick the extreme that you disagreed with. I'd like you to take 
a moment and instead of arguing against the feature that you 
obviously do not like and try to argue for it. I know it will be 
hard and you won't be able to come up with anything, but try 
anyways...



When one had a shit load of types in a single file, it is nice 
to be able to fold them. It is also nice to be able to group 
them in some way(hence the question) and fold the group so 
that large chunks of the file can be visibly reduced.


If you have enough declarations in one file that they call for 
code folding, it may be better to move them to a separate 
module. Public imports and aliases allow doing this without 
breaking any code.


Maybe, maybe not... proves nothing as it is just your preference.

If you would like a way to achieve code folding without 
involving language constructs, I think the starting point would 
be your IDE/editor's D plugin vendor. Once implemented in one 
editor, the syntax could be implemented in others and be 
informally standardized.


That would be fine and dandy, but that is just kicking the can 
down the road to someone else. You should argue on the validity 
of the issue itself and not on


I don't think that it would make sense to introduce it into the 
language syntax proper. The #region syntax in C# makes sense 
for C# because, as already mentioned, the language vendor is 
also the main IDE vendor; but also because C#, like Java, 
requires a lot more boilerplate - writing programs in C# is 
much more tedious without an IDE than with. This is not the 
case of D, which was designed to solve problems that would 
otherwise require boilerplate code in the language itself.


This is not logical. When the designers of C# were creating it, 
in no way did they say "Well, since C#'s IDE will be our IDE we 
will add this feature", and if they weren't they wouldn't have 
added it. They added it because they thought it was a useful 
thing in general. People don't create compilers based on what the 
IDE can or can not do.




Generally speaking, I would recommend to simply avoid code 
folding altogether:


https://blog.codinghorror.com/the-problem-with-code-folding/


Anecdotal. One guys view is not proof of anything. Sometimes it 
is not feasible to split things. The baby shouldn't be thrown out 
with the bath water. Obviously the designers of C# thought it was 
important and useful enough and anyone can hunt for a counter 
example of someone not liking something.



If you start with the conclusion that something is wrong or 
bad(or even right or good) and simply simply opinions as proof, 
you do not prove anything. You should argue on the merits of the 
feature itself and not your own person opinions, desires, and 
wishes.





Re: scope(~this)

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 05:33:28 UTC, thedeemon wrote:

On Monday, 13 March 2017 at 14:28:01 UTC, Inquie wrote:
On Monday, 13 March 2017 at 05:18:18 UTC, Nicholas Wilson 
wrote:

On Sunday, 12 March 2017 at 21:38:44 UTC, Inquie wrote:
Is there any easy way to create a scope for termination of 
the object?


I have a template method that takes a type and allocates and 
deallocates based on that type.


class bar
{
   void foo(T)()
   {
  T x;
  alloc(x);
  scope(~this) dealloc(x); // hypothetical that wraps 
the statement in a lambda and deallocates in the destructor


  ... x must stay allocated until class instance 
termination(has to do with COM, can't release it in foo)

   }

}



I think the feature you're asking for is too 
complicated/involved for a language feature. Because it means 
there must be some implicit array in each object of your 'bar' 
class that holds some number of closures that will be executed 
in destructor. This affects object's memory layout and raises 
questions of allocating memory for those closures and since 
those closures will have pointers to some data (like 'x' here) 
it affects garbage collection. So there are a lot of things to 
be careful about and things that might affect other language 
features we haven't thought about yet. This is something quite 
big and something that affects a lot of code, not just a couple 
of classes you'll write in your one app. Probably it would be 
better to implement it as a library feature. Just make a base 
class having a method for registering such closures and calling 
them in destructor, and inherit from it or just embed it in 
your 'bar'.


Complexity is in the eye of the beholder. Children think many 
things are complex when they are not.


If a library solution could be created that is as seamless as a 
language solution, then I guess it would work.  The downside of a 
library solution is uniformity of syntax and added verbosity.


There is really no any arrays to keep track of or anything like 
that matter you stated. It requires creating a delegate to wrap 
the scope block and a copy of the variable to one on the heap. 
The GC uses arrays and that happens regardless. No reason for the 
compiler to create a new array.


3 steps:

1. Compiler copies local variables to heap(the "closure" part, 
which actually means it is not closing anything as a normal 
delegate would require).


2. The compiler creates a delegate. No big deal, does this in 
many places.


3. The compiler calls all the delegates on destruction. The only 
new part. But not difficult.




Create a ScopeThis(...) and adds no extra overhead would be nice 
but I see that as being more complex. How can we determine what 
are variables that need to be copied to the heap? How can we hook 
in to the ~this? (can't have multiple ones, can we?)


If you can come up with a working ScopeThis that doesn't have any 
more overhead than a language version, I'd be all for it, I don't 
know or see how it could be done.



  ScopeThis!("dealloc(x);")


Must determine that x is a variable(hard?) and copy it to the 
heap(easy). Must create access to any local functions used(e.g., 
if dealloc is local). Then must hook in to ~this to execute the 
code.


It would be nicer to not have to use a string but it would work 
easy since we could use a mixin and modify the string easily once 
we could parse it.







Re: how to assign tuple named Tuple easily

2017-03-14 Thread Inquie via Digitalmars-d-learn

On Monday, 13 March 2017 at 14:15:05 UTC, Adam D. Ruppe wrote:

On Monday, 13 March 2017 at 14:09:58 UTC, Inquie wrote:
Yeah, so, surely though we can extract the names from the 
variable and then supply those like I mentioned?


Yeah, we prolly could, but a simpler thing might be to just use 
typeof:


Tuple!(int, "A")[] x;
x ~= typeof(x[0])(3);


x ~= tuple!x(3)

? Seems like it would probably be rather trivial with a bit of 
template code?


Yeah, tuple could certainly adapt to do that too, but I see you 
would write:



x ~= tuple!typeof(x)(3, 5.0);


and the `tuple!` there is unnecessary: if you already use 
`typeof(x[0])` (you still need a `[0]` in there to get the type 
of the element instead of the array), then you can just 
construct it right there with the next set of parens.


Yeah, I didn't know one could do that. Seems to be better ;) 
Thanks.


Re: Declaring interfaces with a constructor

2017-03-14 Thread David Zhang via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 02:14:53 UTC, evilrat wrote:

like this?
--
[snip]
-

there is also way to do this using templates and duck typing, I 
think it will be more idiomatic way since ranges and stuff 
heavily use it to provide such generalism, though just like you 
say, I would prefer to have strict interface for such use 
case...


Yeah, that's the idea. Though I just thought of a possibility 
using an isPublicInterface template. Is that what you meant by 
templates and duck typing?


Re: What is PostgreSQL driver is most stable?

2017-03-14 Thread Daniel Kozak via Digitalmars-d-learn

Dne 14.3.2017 v 14:21 Daniel Kozak napsal(a):


Dne 14.3.2017 v 14:13 Suliman via Digitalmars-d-learn napsal(a):

I need to develop App that should work on Linux and Windows. It need 
PostgreSQL driver. I tried Vadim's ddbc for PostgreSQL but it's fail 
on x64 version of PostgreSQL and possible will not on x64 PG on Linux 
(I can't test it now).


Could anybody advice me good driver without problems? I seen some 
pg-wrapers on code.dlang.ru, but do not have test all of them.

ddbc works fine for me

s/ddbc/ddb/


Re: What is PostgreSQL driver is most stable?

2017-03-14 Thread Suliman via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 13:21:39 UTC, Paolo Invernizzi wrote:

On Tuesday, 14 March 2017 at 13:13:31 UTC, Suliman wrote:
I need to develop App that should work on Linux and Windows. 
It need PostgreSQL driver. I tried Vadim's ddbc for PostgreSQL 
but it's fail on x64 version of PostgreSQL and possible will 
not on x64 PG on Linux (I can't test it now).


Could anybody advice me good driver without problems? I seen 
some pg-wrapers on code.dlang.ru, but do not have test all of 
them.


I'm using ddb [1], a full-D implementation of the PostgreSQL 
protocol. Not everything it's in place, but it does its works, 
and the codebase is pretty simple, so it's not difficult to 
contribute if you need to add some feature that's missing for 
your use case.


[1] https://github.com/pszturmaj/ddb

---
Paolo


Does it work fine on Linux with x64 Postgres?




Re: What is PostgreSQL driver is most stable?

2017-03-14 Thread Paolo Invernizzi via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 13:13:31 UTC, Suliman wrote:
I need to develop App that should work on Linux and Windows. It 
need PostgreSQL driver. I tried Vadim's ddbc for PostgreSQL but 
it's fail on x64 version of PostgreSQL and possible will not on 
x64 PG on Linux (I can't test it now).


Could anybody advice me good driver without problems? I seen 
some pg-wrapers on code.dlang.ru, but do not have test all of 
them.


I'm using ddb [1], a full-D implementation of the PostgreSQL 
protocol. Not everything it's in place, but it does its works, 
and the codebase is pretty simple, so it's not difficult to 
contribute if you need to add some feature that's missing for 
your use case.


[1] https://github.com/pszturmaj/ddb

---
Paolo


Re: What is PostgreSQL driver is most stable?

2017-03-14 Thread Daniel Kozak via Digitalmars-d-learn

Dne 14.3.2017 v 14:13 Suliman via Digitalmars-d-learn napsal(a):

I need to develop App that should work on Linux and Windows. It need 
PostgreSQL driver. I tried Vadim's ddbc for PostgreSQL but it's fail 
on x64 version of PostgreSQL and possible will not on x64 PG on Linux 
(I can't test it now).


Could anybody advice me good driver without problems? I seen some 
pg-wrapers on code.dlang.ru, but do not have test all of them.

ddbc works fine for me


What is PostgreSQL driver is most stable?

2017-03-14 Thread Suliman via Digitalmars-d-learn
I need to develop App that should work on Linux and Windows. It 
need PostgreSQL driver. I tried Vadim's ddbc for PostgreSQL but 
it's fail on x64 version of PostgreSQL and possible will not on 
x64 PG on Linux (I can't test it now).


Could anybody advice me good driver without problems? I seen some 
pg-wrapers on code.dlang.ru, but do not have test all of them.


Re: Using chunks with Generator

2017-03-14 Thread Era Scarecrow via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 10:00:24 UTC, Tetiana wrote:

Build fails with the following error:


 Just looking at the Documentation, Generator is an InputRange 
and chunks requires a ForwardRange (able to use save 
functionality).


 So the API doesn't match up more or less.

https://dlang.org/phobos/std_concurrency.html#.Generator
https://dlang.org/phobos/std_range.html#chunks


Using chunks with Generator

2017-03-14 Thread Tetiana via Digitalmars-d-learn
I'd like to evaluate values lazily and then process them one by 
one, using e.g. `map`. One of the steps requires processing the 
values in chunks. I was thinking of using a Generator for lazy 
evaluation, but I can't seem to make it work with the `chunks`.


How can I make `std.range.chunks` work with a generator?


import std.stdio;
import std.concurrency: Generator, yield;
import std.range:chunks;
import std.algorithm:map;


void main()
{

auto gen = new Generator!int(
{
foreach (i; 1 .. 10)
yield(i);
});


foreach (n; chunks(gen, 2))
{
writeln(n);
}
}

Build fails with the following error:

source/app.d(18,23): Error: template std.range.chunks cannot 
deduce function from argument types !()(Generator!int, int), 
candidates are:
/usr/include/dmd/phobos/std/range/package.d(6940,15):
std.range.chunks(Source)(Source source, size_t chunkSize) if 
(isForwardRange!Source)

dmd failed with exit code 1.



Re: Phobos function to check if files are identical?

2017-03-14 Thread XavierAP via Digitalmars-d-learn

On Tuesday, 14 March 2017 at 08:12:16 UTC, Andrea Fontana wrote:


First I would check if the files have different size or if they 
are the same file (same path, symlink, etc).


Good idea. Good reason to have it in std.file. There might also 
be platform dependent shortcuts?


Re: Phobos function to check if files are identical?

2017-03-14 Thread Andrea Fontana via Digitalmars-d-learn

On Monday, 13 March 2017 at 17:47:09 UTC, H. S. Teoh wrote:

bool isEqual(string filename1, string filename2) {
import std.algorithm.comparison : equal;
import std.range : zip;
import std.stdio : File, chunks;

auto f1 = File(filename1);
auto f2 = File(filename2);

size_t blockSize = 4096; // or something similar

return f1.chunks(blockSize).equal(f2.chunks(blockSize));
}


First I would check if the files have different size or if they 
are the same file (same path, symlink, etc).