Re: Little demo of allowing basic types to implement interfaces. Was in D.annouce

2013-09-04 Thread Rory McGuire

Just wondering if this exists in the standard library.

I made a function Implements!(T,I) that returns true is a given 
type T implements the interface I.


http://dpaste.dzfl.pl/d7a727fd

I've found it really helps with keeping some code clean such as 
the below:

void main() {
int i = 0x34342343;
writebytes(i);
}


//enum Order { Big };
//interface IRawBytes { ubyte[] bytes(Order); }
interface IRawBytes { ubyte[] bytes(); }

void writebytes(T)(T item) if (Implements!(T, IRawBytes)) {
import std.stdio : writeln;
writeln(item.bytes);
}
ubyte[] bytes(ref int i) {
ubyte* ptr;
ptr = cast(ubyte*)i;
return ptr[0..i.sizeof];
}

If you decide that IRawBytes.bytes should start taking an Order 
parameter you get the same benefits you would have got if you had 
used classes with an interface.


Re: Checking if UFCS function exists for a specific type

2013-08-30 Thread Rory McGuire

On Thursday, 29 August 2013 at 21:10:41 UTC, Rory McGuire wrote:

On Thursday, 29 August 2013 at 21:06:04 UTC, Rory McGuire wrote:

Hi all,

I've got this little ctfe template function that checks if a 
function called member with first argument T exists. Its for 
checking if a type has a custom encoder.


bool hasUFCSmember(T, string member)() {
T v;
	// would be nice if we could use ParameterTypeTuple to get 
the first arg and check for exact type match


return __traits(compiles, mixin(member ~(v)));
}


forum posted when I hit tab. Meant to ask:

Is there a way to make sure that the compiler is not implicitly 
casting T?
Currently it returns true for bool, enum, int etc... even if 
the only function available is for an int.


I also have:
template hasUFCSmember(T, string member) {
	 enum hasUFCSmember = __traits(compiles, mixin(member 
~(T.init)));

}
But it doesn't work for types such as string[string] because 
T.init is null.


Any help will be greatly appreciated.

Thanks,
R


I suppose I can avoid the implicit casts for function lookup by 
using Typedef.


Thanks,
R


Checking if UFCS function exists for a specific type

2013-08-29 Thread Rory McGuire

Hi all,

I've got this little ctfe template function that checks if a 
function called member with first argument T exists. Its for 
checking if a type has a custom encoder.


bool hasUFCSmember(T, string member)() {
T v;
	// would be nice if we could use ParameterTypeTuple to get the 
first arg and check for exact type match


return __traits(compiles, mixin(member ~(v)));
}


Re: Checking if UFCS function exists for a specific type

2013-08-29 Thread Rory McGuire

On Thursday, 29 August 2013 at 21:06:04 UTC, Rory McGuire wrote:

Hi all,

I've got this little ctfe template function that checks if a 
function called member with first argument T exists. Its for 
checking if a type has a custom encoder.


bool hasUFCSmember(T, string member)() {
T v;
	// would be nice if we could use ParameterTypeTuple to get the 
first arg and check for exact type match


return __traits(compiles, mixin(member ~(v)));
}


forum posted when I hit tab. Meant to ask:

Is there a way to make sure that the compiler is not implicitly 
casting T?
Currently it returns true for bool, enum, int etc... even if the 
only function available is for an int.


I also have:
template hasUFCSmember(T, string member) {
	 enum hasUFCSmember = __traits(compiles, mixin(member 
~(T.init)));

}
But it doesn't work for types such as string[string] because 
T.init is null.


Any help will be greatly appreciated.

Thanks,
R


Re: Using getchar

2010-09-10 Thread Rory McGuire
Its not skipping its looping on a\r\n if you're on windows.

Linux it does the same but only a\n.

Not sure how you'd make it so that you don't have to wait for the 
return press. Probably has something to do with console settings,
which are probably platform dependent.

-Rory


Andrej Mitrovic wrote:

 I have some D1 code that I'm transfering to D2, and it's using 
getchar. I
 think I need to flush the buffer or something because the loop tends 
to
 skip:
 
 import std.c.stdio;
 import std.stdio;
 
 void main()
 {
 char k;
 
 for(int i = 0; i  10; i++)
 {
 writef(Press key #%d:\t\n, i);
 k = cast(char)getchar();
 }
 }
 
 E.g.:
 Press key #0:
 a
 Press key #1:
 Press key #2:
 b
 Press key #3:
 Press key #4:
 c
 Press key #5:
 Press key #6:
 
 I guess I could use scanf() instead.. or maybe something more D-ish
 perhaps? :)
 
 Someone on the NGs started creating some user-friendly input 
functions,
 something like getInput!char(variable), or similar. But I can't find 
the
 topic, anyone know the link perhaps? It was fairly recent that 
someone
 posted it.



Re: dmd: Module X conflicts with itself (Was: Re: RDMD on Windows)

2010-08-22 Thread Rory Mcguire
Andrej Mitrovic wrote:

 Doh! I swear I've read somewhere that a module declaration needs to have
 the same name as the *file name*. I didn't know I had to add the path as
 well. That makes the modules work now.
 
 In fact, I probably just read this one line in the docs:
 
 The ModuleDeclaration sets the name of the module and what package it
 belongs to. *If absent, the module name is taken to be the same name
 (stripped of path and extension) of the source file name.*
 
 But I didn't pay attention to the package stuff.
 
 Thanks Nick for the help, I was going slightly mad there for a second. :p
 
 
 Nick Sabalausky Wrote:
 
 snip

In Java yes. I D you can use the module declaration to move a module.
e.g.
filename: socket.d;
module: alt.socket;

to import you'd do import alt.socket; even if the file is in the same
directory as the module using the file.


Re: String literals have only one instance?

2010-08-20 Thread Rory Mcguire
Rory Mcguire wrote:

 Are all string literals that have the same value initialized to the same
 address?
 
 void main() {
 string same() {
 return This;
 }
 assert(This is same());
 assert(This is This);
 }
 
 
 Can this be relied upon?


Interesting thanks guys.

Was just curious about the speed of comparisons for string literals. Because
I believe the string comparisons check if a string is another string 
first.


String literals have only one instance?

2010-08-19 Thread Rory Mcguire
Are all string literals that have the same value initialized to the same 
address?

void main() {
string same() {
return This;
}
assert(This is same());
assert(This is This);
}


Can this be relied upon?


Re: inheriting ctors?

2010-08-09 Thread Rory Mcguire
Philippe Sigaud wrote:

 On Fri, Aug 6, 2010 at 21:59, Rory Mcguire rjmcgu...@gm_no_ail.com
 wrote:
 

 Here is a possible solution to your problem:

 -Rory
 
 
 I believe you can get the type of A. Isn't it typeof(super) or
 std.traits.BaseClassesTuple!B[0] ? B in the latter case being typeof(this)
 That way, there is no need for the user to provide A, it's automatically
 found by the template.
 Warning: I did not test this.
 
 And, we know the constructs are of type 'A function(someTypes)'  [*], so
 the 'A function' part is redundant.
 Hence, the user only needs to provide for the args types and that makes
 for a cleaner call.
 
 * either as a list :
 mixin(InheritConstructors!(int, double, string)); // I want to inherit
 the constructors taking one type, build me the __ctors for int, double and
 string
 
 * or, in the case of multi-parameters constructors, wrap them in a tuple:
 mixin(InheritConstructors!(int, double, Tuple!(int, double)); // I
 want
 super(int), super(double) and super(int, double)
 
 That means iterating on the type list, and determining if the current type
 is a tuple or not
 * if its a 'normal' type, create the corresponding contructor
 * if it's a Tuple, crack it open and get the types, using the .Types alias
 std.typecons.Tuples have. Creating a constructor from this typetuple is no
 different from creating it for one type.
 
 To determine if something is a std.typecons.Tuple, you cannot use an is()
 expression: they do not allow multiple types:
 
 enum bool isTuple = is(T == Tuple!U, U...); // no. U... is not allowed.
 Hmm, enhancement request?
 
 So, you can either rely on it having a .Types 'member':
 
 template isTuple(T)
 {
   enum bool isTuple = is(T.Types);
 }
 
 Pb: that will flag as tuples any type that exposes a .Types alias.
 
 Or use a function accepting a Tuple:
 
 template isTuple(T)
 {
 enum bool isTuple = is(typeof({
void foo(U...)(Tuple!U t) {}; // this
 function accepts only tuples
foo(T.init); // test it
   }()));
 }
 
 It's ugly as a rat's ass, but it's more solid than the former template.
 
 
 Philippe
 
 [*] btw, shouldn't that be A delegate(someTypes)???

I'll see what I can do to shorten it but I'm not sure how to iterate over 
the Selectors inside the foreach and still be able to skip unselected 
constructors. Hmmm I suppose I could use a temporary boolean or something.


I don't use A delegate(someTuypes) because the compiler says that the type
of the constructors is for instance: A function(int x)




Re: inheriting ctors?

2010-08-09 Thread Rory Mcguire
I had been trying to use AutoImplement to make something before but it gave 
me weird errors.
I'm going to try using it for implementing this when I get some time.

Andrej Mitrovic wrote:

 Here's an example:
[snip]


Re: inheriting ctors?

2010-08-06 Thread Rory Mcguire
Philippe Sigaud wrote:

 On Fri, Aug 6, 2010 at 11:43, Rory Mcguire rjmcgu...@gm_no_ail.com
 wrote:
 
 
 I've been trying to make a template for this but it seems that dmd still
 won't allow me to get the parameters of the constructors. dmd Seems to
 think
 that I'm trying to use it as a property.


 
 void main() {
foreach (m; __traits(getOverloads, A, __ctor)) {
pragma(msg, m.stringof); // it thinks I'm calling m
}
 }

 constructors.d(34): Error: constructor constructors.A.this (int x) is not
 callable using argument types ()

 
 This is my new once-a-day bug :(
 Using a function alias, and being unable to call properties on it, because
 DMD thinks I'm calling it. Man, it's no property, just a name!
 
 Anyway, just pragma(msg, m) works, strangely.
 I think I found a way to use m, somewhat:
 
 void main() {
foreach (m; __traits(getOverloads, A, __ctor)) {
pragma(msg, m); // it thinks I'm calling m
typeof(m) tmp = m;
 writeln( (ParameterTypeTuple!tmp).stringof); // (int), (double),
 (string)
 writeln( (ParameterTypeTuple!m).stringof); // (int), (int), (int)
 writeln( typeof(m).stringof); // A function(int x), A
 function(double x), A function(string s)
}
 }
 
 using ParameterTypeTuple!m directly does not differentiate the m's. But
 using a temporary pointer, it seems to work.
 
 Oh and I even get the arguments names !
 
 
 Philippe

Thanks!! works now. Now we just need to be able to select which constructors 
we actually want.

string inheritconstructors_helper(alias T)() {
string s;
foreach (m; __traits(getOverloads, T, __ctor)) {
string args, args1;
foreach (i, cons; ParameterTypeTuple!(typeof(m))) {
pragma(msg, cons.stringof);
args ~= ,~cons.stringof~ v~to!string(i);
args1 ~= ,v~to!string(i);
}
args = args.length  1 ? args : args[1..$];
args1 = args1.length  1 ? args1 : args1[1..$];
s ~= this(~args~) { super(~args1~); }\n;
}
return s;
}

class A {
int i;
//private this() {}
this(int x) {
i = x;
}
this(float x) {
i = cast(int)x; // ignore bad code
}
this(string s, int mul) { // test multiple args
i = to!int(s) * mul;
}
}
class B : A {
mixin(inheritconstructors_helper!A());
//  InheritConstructors!A;
}



void main() {
A a = new B(4);
a = new B(42, 2);
}







Re: inheriting ctors?

2010-08-06 Thread Rory Mcguire
Rory Mcguire wrote:

 Philippe Sigaud wrote:
 
 On Fri, Aug 6, 2010 at 11:43, Rory Mcguire rjmcgu...@gm_no_ail.com
 wrote:
 
 
 I've been trying to make a template for this but it seems that dmd still
 won't allow me to get the parameters of the constructors. dmd Seems to
 think
 that I'm trying to use it as a property.


 
 void main() {
foreach (m; __traits(getOverloads, A, __ctor)) {
pragma(msg, m.stringof); // it thinks I'm calling m
}
 }

 constructors.d(34): Error: constructor constructors.A.this (int x) is
 not callable using argument types ()

 
 This is my new once-a-day bug :(
 Using a function alias, and being unable to call properties on it,
 because DMD thinks I'm calling it. Man, it's no property, just a name!
 
 Anyway, just pragma(msg, m) works, strangely.
 I think I found a way to use m, somewhat:
 
 void main() {
foreach (m; __traits(getOverloads, A, __ctor)) {
pragma(msg, m); // it thinks I'm calling m
typeof(m) tmp = m;
 writeln( (ParameterTypeTuple!tmp).stringof); // (int), (double),
 (string)
 writeln( (ParameterTypeTuple!m).stringof); // (int), (int), (int)
 writeln( typeof(m).stringof); // A function(int x), A
 function(double x), A function(string s)
}
 }
 
 using ParameterTypeTuple!m directly does not differentiate the m's. But
 using a temporary pointer, it seems to work.
 
 Oh and I even get the arguments names !
 
 
 Philippe
 
 Thanks!! works now. Now we just need to be able to select which
 constructors we actually want.
 
 string inheritconstructors_helper(alias T)() {
 string s;
 foreach (m; __traits(getOverloads, T, __ctor)) {
 string args, args1;
 foreach (i, cons; ParameterTypeTuple!(typeof(m))) {
 pragma(msg, cons.stringof);
 args ~= ,~cons.stringof~ v~to!string(i);
 args1 ~= ,v~to!string(i);
 }
 args = args.length  1 ? args : args[1..$];
 args1 = args1.length  1 ? args1 : args1[1..$];
 s ~= this(~args~) { super(~args1~); }\n;
 }
 return s;
 }
 
 class A {
 int i;
 //private this() {}
 this(int x) {
 i = x;
 }
 this(float x) {
 i = cast(int)x; // ignore bad code
 }
 this(string s, int mul) { // test multiple args
 i = to!int(s) * mul;
 }
 }
 class B : A {
 mixin(inheritconstructors_helper!A());
 //  InheritConstructors!A;
 }
 
 
 
 void main() {
 A a = new B(4);
 a = new B(42, 2);
 }

Got selection working:

string inheritconstructors_helper(alias T,Selectors...)() {
string s;

foreach (m; __traits(getOverloads, T, __ctor)) {
string args, args1;
pragma(msg, typeof(m));
/*foreach (sel; Selectors) {
pragma(msg, sel, is (sel == typeof(m)));
continue top;
}*/
if (staticIndexOf!(typeof(m), Selectors)==-1) {
continue;
}
foreach (i, cons; ParameterTypeTuple!(typeof(m))) {
pragma(msg, cons.stringof);
args ~= ,~cons.stringof~ v~to!string(i);
args1 ~= ,v~to!string(i);
}
args = args.length  1 ? args : args[1..$];
args1 = args1.length  1 ? args1 : args1[1..$];
s ~= this(~args~) { super(~args1~); }\n;
}
return s;
}



Usage:

class B : A {
mixin(inheritconstructors_helper!(A,TypeTuple!(A function(string,int)
,A function(int)))());
}



Re: hijacking a class's members

2010-08-04 Thread Rory Mcguire
Mafi wrote:

 Am 04.08.2010 12:11, schrieb Rory Mcguire:
 Hi,

 The code below is my beginning to attempt a class which implements any
 class and throws an exception if one tries to access any member of that
 class.

 Problem is that if I use:
 auto a1 = noinit!(A)();

 it works and accesses the int x() {...} member of the generated class,
 but if I use:
 A a1 = noinit!(A)();

 it accesses A.x instead of the generated classes x.

 So am I wrong in making a sub class have a member function which hides a
 parent class's member variable or is the compiler wrong and it should
 generate a call to generated sub class?


 Thanks!!!
 -Rory
 Hi,
 if x is a field (ie a member variable) it's statically bound. In your
 example it is a field so it gets A.x of your subclass which is still
 there becuase of the methoda of A which could use A.x.
 Fields have to be statically bound because there's no covariance
 guarateed with them. Use getters and setters instead.
 BTW are @propertys statically or dynamically bound. They're kind of
 both: fields and methods.
 
 Mafi

Thats what feels weird to me. a.x can result in different things happening 
even though x exists in both A and the generated class. However the 
generated class has two fields called x one you can't access anymore and 
the @property one.
When I create an instance of the generated class I would expect it to always 
to the same thing if I use one of its methods/properties/etc...
Kind of like you would expect the following to print out hello 2:
class A {
string toString() { return hello; }
}
class B : A {
string toString() { return super.toString() ~  2; }
}
void main() {
A a = new B();
writeln(a.toString()); // uses B.toString()
}

What I've got is:
class A {
int x;
}
class B : A {
int x() { throw new Exception(); }
}
void main() {
A a = new B();
writeln(a.x); // this accesses A.x not B.x
}

just seems like properties are not quite right or something.

-Rory



Re: hijacking a class's members

2010-08-04 Thread Rory Mcguire
Mafi wrote:

 Thats what feels weird to me. a.x can result in different things
 happening even though x exists in both A and the generated class. However
 the generated class has two fields called x one you can't access
 anymore and the @property one.
 When I create an instance of the generated class I would expect it to
 always to the same thing if I use one of its methods/properties/etc...
 Kind of like you would expect the following to print out hello 2:
 class A {
  string toString() { return hello; }
 }
 class B : A {
  string toString() { return super.toString() ~  2; }
 }
 void main() {
  A a = new B();
  writeln(a.toString()); // uses B.toString()
 }

 What I've got is:
 class A {
  int x;
 }
 class B : A {
  int x() { throw new Exception(); }
 }
 void main() {
  A a = new B();
  writeln(a.x); // this accesses A.x not B.x
 }

 just seems like properties are not quite right or something.

 -Rory

 
 If you want that to work, both x have to be virtual (ie dynamically
 bound). In D all non-final non-ststic clsss-methods are virtual(1).
 Consider the following:
 ///
 class A {
int x = 0;
int getX() { //-- it's virtual
  return x;
}
 }
 
 class B : A{
int x = 5;
override int getX() { //-- it's virtual too
  return x;
}
 }
 
 void thinAboutA(A a) {
/* Now a call to a non virtual method
 * which results in vtbl lookup. a's vtbl
 * contains B.getX().
writeln(a.getX());
/* Non virtual field.
 * Has to be statically bound
 * to a lookup in A.x
 */
writeln(a.x);
 }
 
 void main() {
thinkAboutA(new B);
 }
 
 
 Fields have to be statically bound bcause the compiler doesn't enforce
 covariance with fields. So you can:
 ///
 class C : A {
string x = ;
 }
 
 void main()  {
thinkAboutA(new C); //Should evrything crash now? I won't.
 }
 //
 
 1) I'm not sure about @propertys.


cool thanks

good example


Re: various questions

2010-08-03 Thread Rory Mcguire
Jason Spencer wrote:

 == Quote from Rory Mcguire (rjmcgu...@gm_no_ail.com)'s article
 Jason Spencer wrote:
  == Quote from Rory Mcguire (rjmcgu...@gm_no_ail.com)'s article
  Jason Spencer wrote:
 
   I nievely went and replaced foreach (t;
 Iota!(str_types.length))
   with foreach (t; str_types.length), since the length of that
   array is known at compile-time.
 
  Can't use 0 .. str_types.length in the foreach
  because compiler is expecting Integer constants so it can make
  the template foo into actual code.
 
 This is the part I'm still not getting.  Why shouldn't
 
foreach (t; 0..3)
 
 work?  Those are integer constants.
 
 Actually, I think I'm getting it.  str_types.length is actually (or
 close to) an integer literal, but t is not.  t over a range is an int
 variable.  So at best, the compiler will infer the type of t and try
 to get TypeTuple![int] from the mixin, which doesn't help.  But it
 works in Iota because it only needs a value, and the length property
 is not a variable, but a compile-time constant.
 
 I'm not sure what magic gets worked when t is bound to a TypeTuple
 that has int literals, but I'm guessing t in that case is not an int
 variable, but a compile-time type variable, and it iterates over int
 literals.  Those work with templ.  What I really want to know is does
 that foreach run at compile-time or run-time?  I suspect compile-time
 because it iterates over type variables.  But documentation is shakey
 :)
 
 
 
 I convert str_types.length to its actual value below:
 foreach (t; 3) {
 ...
 }
 You can't do that (dmd : t.d(6): Error: int is not an aggregate
 type)
 
 Yeah, I mis-typed orginally.  It was foreach (t;
 0..str_types.length) as a range.

The foreach using Iota is unrolled at compile time, bearofile mentioned this 
somewhere as well.



Re: various questions

2010-07-30 Thread Rory Mcguire
Jason Spencer wrote:

 Ok, I've gone over this, adapted it, and mostly understand it.  I just
 have one question left:
 
 == Quote from bearophile (bearophileh...@lycos.com)'s article
 template Iota(int stop) {
 ...
 alias TypeTuple!(Iota!(stop-1), stop-1) Iota;
 }
 ...
 foreach (t; Iota!(str_types.length))
 
 What happens at compile-time with this foreach loop?
 
 I nievely went and replaced foreach (t; Iota!(str_types.length))
 with foreach (t; str_types.length), since the length of that array
 is known at compile-time.  That of course bombed, but I don't quite
 get why.  Is the compiler actually evaluating the foreach loop at
 compile time?  How could it, when the body makes run-time checks?  If
 it's not, why doesn't my change work?
 
 Jason

your replacement tries to loop over an uint called str_types.length. Never 
gonna happen.

Iota!(str_types.length) seems to generate str_types.length(a number of) 
integer indexes. Can't use 0 .. str_types.length in the foreach because 
compiler is expecting Integer constants so it can make the template foo 
into actual code.




Re: various questions

2010-07-30 Thread Rory Mcguire
Jason Spencer wrote:

 == Quote from Rory Mcguire (rjmcgu...@gm_no_ail.com)'s article
 Jason Spencer wrote:
 
  I nievely went and replaced foreach (t; Iota!(str_types.length))
  with foreach (t; str_types.length), since the length of that
  array is known at compile-time.
 
 your replacement tries to loop over an uint called str_types.length.
 Never gonna happen.
 Iota!(str_types.length) seems to generate str_types.length(a number
 of)integer indexes. Can't use 0 .. str_types.length in the foreach
 because compiler is expecting Integer constants so it can make the
 template foo into actual code.
 
 Not quite sure I follow.  I think you're saying the range in foreach
 has to be actual literals, and not just an expression that can be
 evaluated at compile time to generate the same range...close?
 
 If that's the case, then why does it work to instantiate Iota! with
 str_types.length?  It can obviously get the value behind it at compile
 time.  I'm still missing something.
 
 Jason

I convert str_types.length to its actual value below:
foreach (t; 3) {
...
}

You can't do that (dmd : t.d(6): Error: int is not an aggregate type)





Re: Stack traces on exceptions in D2?

2010-07-29 Thread Rory Mcguire
Nick Sabalausky wrote:

 Is there a way to get stack traces on exceptions in D2?
What OS.

I'm on linux and I get stack traces.


Re: Stack traces on exceptions in D2?

2010-07-29 Thread Rory Mcguire
Nick Sabalausky wrote:

 Nick Sabalausky a...@a.a wrote in message
 news:i2rbht$22v...@digitalmars.com...
 Rory Mcguire rjmcgu...@gm_no_ail.com wrote in message
 news:i2rafu$20l...@digitalmars.com...
 Nick Sabalausky wrote:

 Is there a way to get stack traces on exceptions in D2?
 What OS.

 I'm on linux and I get stack traces.

 Windows.

 Must be a debug-only thing though (not sure why I thought otherwise).
 I've been unable to actually build in debug mode though, because 2.046
 gives me phobos errors if I use debug mode, and 2.076 can't do
 array(filter()) which is a breaker for me. I guess I could try 2.045.
 
 Hmm, weird, I'm not getting the Phobos error with debug-mode on 2.076 now.
 But still not getting stack traces though, even with both -debug and -g

interesting, I get them on 2.046 with and without -debug but not with -
release.


Re: SIGSEGV in rt_finalize

2010-07-29 Thread Rory Mcguire
Steven Schveighoffer wrote:

 On Wed, 28 Jul 2010 11:45:59 -0400, Rory Mcguire rjmcgu...@gm_no_ail.com
 wrote:
 
 Hi guys,

 I have a 265 line program that gets a segmentation fault if I don't
 comment
 out this while loop(I am not using delete or anything like it):
 /+  while (lines.length  0  line.length  3  line[3]=='-') {
 line ~= lines[0];
 lines = lines[1..$];
 }+/

 Any Ideas on how to track this one down?
 
 No, please post the whole code, or a reduced example.  What compiler
 version/platform?
 
 -Steve

I'll try make a reduced example.


Re: struct opCall error messages

2010-07-28 Thread Rory Mcguire
Jacob Carlborg wrote:

 On 2010-07-26 14:27, Rory Mcguire wrote:
 Hi,

 I'm not sure this is in bugzilla, I tried finding something mentioning it
 but coudn't.

 Compiling the below code results in the dmd compiler printing:
 struct_bad_error.d(8): Error: 'this' is only defined in non-static member
 functions, not inner

 
 struct S {
 S opCall() {S s; return s;}
 }
 void main() {
 S s;
 //s = S(); // decent error message: struct_bad_error.d(6):
 // Error: need 'this' to access member opCall
 void inner() {
 s = S();
 }
 }
 =

 What to do? Also found that having an empty () after the struct name is
 not the best error message: struct_bad_error.d(5): Error: struct
 struct_bad_error.S() is used as a type

 Surely it could tell me I need to put an Identifier in the ()

 -Rory
 
 Perhaps you want a static opCall ?
 
 S foo;
 foo(); // calls opCall
 S(); // calls static opCall
 


doh! [slaps head]

Thanks


Re: Threading errors.

2010-07-27 Thread Rory Mcguire
Philippe Sigaud wrote:

 On Mon, Jul 26, 2010 at 19:11, dcoder dco...@devnull.dev wrote:
 
 == Quote from Rory Mcguire (rjmcgu...@gm_no_ail.com)'s article
  Dmitry Olshansky wrote:

 
 
 std.typecons.Tuple fields cannot be indexed like arrays, Andrei made a
 mistake. To access field  #n, use ._n or .field[n]. There is no difference
 between the two.
 
 void writer() {
  for( ;; ) {
auto msg = receiveOnly!(Tid, int)(); // msg is a Tuple!(Tid, int),
msg._0
 is a Tid, msg._1 is an int.
writeln( Secondary thread: , msg._1);
msg._0.send(thisTid);
  }
 }
 
 Also, in my case, the return; in writer must be commented out, or DMD
 complains it cannot be reached.
 
 
 Philippe


Interesting, I didn't have to comment out return; using dmd 2.047 on linux


Re: Threading errors.

2010-07-27 Thread Rory Mcguire
Philippe Sigaud wrote:

 On Tue, Jul 27, 2010 at 11:25, Rory Mcguire rjmcgu...@gm_no_ail.com
 wrote:
 

  Also, in my case, the return; in writer must be commented out, or DMD
  complains it cannot be reached.

 
 

 Interesting, I didn't have to comment out return; using dmd 2.047 on
 linux

 
 I think I have -w (warnings treated as errors?) always checked. That's my
 Code::Blocks default configuration for DMD.
 I was on Windows for this test. I never cheked if there was any difference
 between OSes for this :-)

:) thanks Philippe


Re: D and cygwin io.

2010-07-27 Thread Rory Mcguire
dcoder wrote:

 Hello.  Here's a short program that works in a dos window:
 
 import std.stdio;
 
 void main() {
 
   writef( What is your name?);
 
   string name = readln();
   writefln( Hello  ~ name);
 }
 
 The program prints a prompt without a newline and the user enters a name
 and a greeting is printed.
 
 The same program does not seem to work when at a cygwin prompt.  The
 program
 seems to pause.  It is actually waiting for input.  So, if I type in a
 name and hit return, the prompt and the greeting appears as expected but
 on one line.
 
 I can change writef to writefln and it will work on the cygwin prompt and
 on the dos prompt, but now a newline will be added after the prompt
 message.
 
 I'm wondering how can I fix this?  I am using bash shell on cygwin.
 
 
 thanks.


try flushing the output after the write: stdout.flush();


struct opCall error messages

2010-07-26 Thread Rory Mcguire
Hi,

I'm not sure this is in bugzilla, I tried finding something mentioning it 
but coudn't.

Compiling the below code results in the dmd compiler printing:
struct_bad_error.d(8): Error: 'this' is only defined in non-static member 
functions, not inner


struct S {
S opCall() {S s; return s;}
}
void main() {
S s;
//s = S(); // decent error message: struct_bad_error.d(6):
// Error: need 'this' to access member opCall
void inner() {
s = S();
}
}
=

What to do? Also found that having an empty () after the struct name is not 
the best error message: struct_bad_error.d(5): Error: struct 
struct_bad_error.S() is used as a type

Surely it could tell me I need to put an Identifier in the ()

-Rory


std.socket.TcpSocket.flush

2010-07-26 Thread Rory Mcguire
Hi,

What is one supposed to use to flush a TcpSocket.

flush doesn't seem to exist, should I really just use the c function?

-Rory


Re: std.socket.TcpSocket.flush

2010-07-26 Thread Rory Mcguire
Heywood Floyd wrote:

 Rory Mcguire Wrote:
 
 Hi,
 
 What is one supposed to use to flush a TcpSocket.
 
 flush doesn't seem to exist, should I really just use the c function?
 
 -Rory
 
 
 Was in a similar situation, found this:
http://stackoverflow.com/questions/855544/is-there-a-way-to-flush-a-
posix-socket
 
 I thought a socket needed to be flushed because curl and ab hanged when
 GETting from my server. Turns out I was just not sending the correct
 HTTP-headers...
 
 /HF

Thanks. I've made this before but it was about 3 years ago now, and I can't 
remember what I did. Perhaps it was just TCP_NODELAY.

telnet,smtp,http1.1, etc... all rely on the ability to send data without the 
while the client waits for a specific line.
I'm sending a line when the client connects, which the client has to read in
order to acknowledge, with a write but it never gets the data from the 
server.

Suppose I'll have to find my backups... somewhere :(.


Detecting a property setter?

2010-07-19 Thread Rory McGuire

Hi,

Does anyone know how to detect if there is a setter for a property? The  
code below prints the same thing for both
the setter and the getter of front:

==
import std.traits;

class Foo {
 uint num;

 @property ref uint front() {
 return num;
 }
 @property void front(uint i) {
 num = i;
 }

 ref uint front2() {
return num;
 }
}

template isProperty(alias func) if (isCallable!(func)) {
enum isProperty = (functionAttributes!(func)   
FunctionAttribute.PROPERTY)==0 ? false : true;
}

template hasSetter(alias func) if (isCallable!(func)) {
enum hasSetter = (isProperty!(func)  ParameterTypeTuple!(func).length 
  
0  ReturnType!(func).stringof != void) ? true : false;
}

void main() {
 Foo foo;
pragma(msg, hasSetter!(foo.front));

static if (isProperty!(foo.front)) {
pragma(msg, property);
} else {
pragma(msg, not a property);
}

alias MemberFunctionsTuple!(Foo,front) fronts;
foreach (s; fronts) {
pragma(msg, ReturnType!(s)); // this line just prints uint 
for both  
front properties!
}
}



Is this a compiler bug? Or am I wrong again?

Thanks
Rory


www.neonova.co.za: http://cf.neonova.co.za/9YXp
View: https://mail1.clearformat.com/vcard.php?uid=11pid=10
Beta Test Advert: http://fwd.clearformat.com/9YXn
inline: logo.jpginline: ff2d54b.jpg

Re: Detecting a property setter?

2010-07-19 Thread Rory McGuire
On Mon, 19 Jul 2010 22:06:14 +0200, Simen kjaeraas  
simen.kja...@gmail.com wrote:



Rory McGuire rmcgu...@neonova.co.za wrote:


Does anyone know how to detect if there is a setter for a property? The
code below prints the same thing for both
the setter and the getter of front:

==
import std.traits;

class Foo {
 uint num;

 @property ref uint front() {
 return num;
 }
 @property void front(uint i) {
 num = i;
 }

 ref uint front2() {
return num;
 }
}

template isProperty(alias func) if (isCallable!(func)) {
enum isProperty = (functionAttributes!(func) 
FunctionAttribute.PROPERTY)==0 ? false : true;
}

template hasSetter(alias func) if (isCallable!(func)) {
	enum hasSetter = (isProperty!(func)   
ParameterTypeTuple!(func).length 

0  ReturnType!(func).stringof != void) ? true : false;
}


For what it's worth, I would simply check if the property allows  
assignment. i.e.:


template hasSetter(alias func) if (isCallable!(func)) {
 enum hasSetter = isProperty!(func) 
 is( typeof( (){ func = ReturnType!(func).init; } ) );
}



Hehe good solution, never even crossed my mind.
And it doesn't match ref return types such as the following signature.

ref uint front() { return num; }

My test code below:
===
import std.traits;

class Foo {
uint num;

@property ref uint front() {
return num;
}
/+@property void front(uint i) {
num = i;
}+/

ref uint front2() {return num;}
}

template isProperty(alias func) if (isCallable!(func)) {
	enum isProperty = (functionAttributes!(func)   
FunctionAttribute.PROPERTY)==0 ? false : true;

}

template hasSetter(alias func) if (isCallable!(func)) {
enum hasSetter = isProperty!(func) 
is( typeof( (){ func = ReturnType!(func).init; } ) );
}

void main() {
Foo foo;
pragma(msg, hasSetter!(foo.front)); // is the return type null (setter)

static if (isProperty!(foo.front)) {
pragma(msg, property);
} else {
pragma(msg, not a property);
}

alias MemberFunctionsTuple!(Foo,front) fronts;
foreach (s; fronts) {
pragma(msg, hasSetter!(s));
}

}


Could be used in a GUI library for checking which properties of a class  
are editable and which are only for display.

And tell you about it at compile time.


Thanks!


Re: Detecting a property setter?

2010-07-19 Thread Rory McGuire
On Mon, 19 Jul 2010 23:25:01 +0200, Jonathan M Davis  
jmdavisp...@gmail.com wrote:



On Monday, July 19, 2010 13:42:51 Philippe Sigaud wrote:
On Mon, Jul 19, 2010 at 22:06, Simen kjaeraas  
simen.kja...@gmail.comwrote:

 template hasSetter(alias func) if (isCallable!(func)) {

enum hasSetter = isProperty!(func) 

is( typeof( (){ func = ReturnType!(func).init; } ) );

 }

In that case, for the second func, the one you call ReturnType on, how  
does
the compiler knows it must take the ref uint one (the getter) and not  
the

void func() one?


Philippe


I don't think that you're supposed to be able to have a getter property
returning a ref at the same time that you have a setter property with  
the same

name. It certainly sounds like it should be a bug in any case.

- Jonathan M Davis


I suppose it would be seen as a bug because it possibly circumvents the  
getter/setter

philosophy (If you return the internal value anyway).


Re: Detecting a property setter?

2010-07-19 Thread Rory McGuire



On Mon, 19 Jul 2010 22:42:51 +0200, Philippe Sigaud philippe.sig...@gmail.com wrote:On Mon, Jul 19, 2010 at 22:06, Simen kjaeraas simen.kja...@gmail.com wrote:
template hasSetter(alias func) if (isCallable!(func)) {
    enum hasSetter = isProperty!(func) 
        is( typeof( (){ func = ReturnType!(func).init; } ) );
}In that case, for the second func, the one you call ReturnType on, how does the compiler knows it must take the ref uint one (the getter) and not the void func() one?Philippe

Simen is using the fact that the compiler already has to figure out if there is an overload that matches the requirements. So it ends uptaking the only one that works. Since it seems to ignore the ref return type property, the property that takes an uint argument must have ahigher precedence (gets checked if it works first).I wonder if its because Walter probably implemented function overloading before properties and ref return types. Hopefully its a languagefeature and not just a implementation side effect.-Rory

Anyone know why this CTFE isn't working?

2010-07-16 Thread Rory McGuire




import std.stdio;struct State {	string s; string getString() { return s; }	static State opCall(string s) {		State ret;		ret.s = s;		return ret;	}}void main() {	auto s = State("adf");	pragma(msg, s.getString());}dmd Output: (line 14 is the pragma statement)struct.d(14): Error: variable s cannot be read at compile timestruct.d(14): Error: cannot evaluate s.getString() at compile times.getString()

Rory McGuire
R
Tel : +27 (033) 386 7263

Cell : +27 (082) 856 3646
Email: rmcgu...@neonova.co.za
Website: www.neonova.co.za
VCard: View


  This email and its attachments may be confidential and are intended solely for the use of the individual to whom it is addressed. Any views or opinions expressed are solely those of the author and do not necessarily represent those of NeoNova. If you are not the intended recipient of this email and its attachments, you must take no action based upon them, nor must you copy or show them to anyone. Please contact the sender if you believe you have received this email in error.



Re: Anyone know why this CTFE isn't working?

2010-07-16 Thread Rory McGuire

Sorry about the html

On Fri, 16 Jul 2010 11:46:48 +0200, Rory McGuire rmcgu...@neonova.co.za  
wrote:


import std.stdio;

struct State {
string s; string getString() { return s; }
static State opCall(string s) {
State ret;
ret.s = s;
return ret;
}
}

void main() {
auto s = State(adf);
pragma(msg, s.getString());
}

dmd Output: (line 14 is the pragma statement)

struct.d(14): Error: variable s cannot be read at compile time
struct.d(14): Error: cannot evaluate s.getString() at compile time
s.getString()


Re: Anyone know why this CTFE isn't working?

2010-07-16 Thread Rory McGuire
On Fri, 16 Jul 2010 11:58:57 +0200, Lars T. Kyllingstad  
pub...@kyllingen.nospamnet wrote:



On Fri, 16 Jul 2010 11:46:48 +0200, Rory McGuire wrote:


import std.stdio;

struct State {
  string s; string getString() { return s; } static State opCall(string
  s) {
  State ret;
  ret.s = s;
  return ret;
  }
}

void main() {
  auto s = State(adf);
  pragma(msg, s.getString());
}

dmd Output: (line 14 is the pragma statement)

struct.d(14): Error: variable s cannot be read at compile time
struct.d(14): Error: cannot evaluate s.getString() at compile time
s.getString()


It's not working because s isn't a compile-time quantity.  Try:

  enum s = State(adf);

-Lars


Awesome thanks, worked.

So is the difference that auto s is a Struct which can change whereas  
enum s is a constant?

If it is a constant its just s that is constant right?

Thanks Lars


-Rory


Re: Anyone know why this CTFE isn't working?

2010-07-16 Thread Rory McGuire
On Fri, 16 Jul 2010 12:05:02 +0200, Jonathan M Davis  
jmdavisp...@gmail.com wrote:



On Friday 16 July 2010 02:46:48 Rory McGuire wrote:

import std.stdio;

struct State {
  string s; string getString() { return s; }
  static State opCall(string s) {
  State ret;
  ret.s = s;
  return ret;
  }
}

void main() {
  auto s = State(adf);
  pragma(msg, s.getString());
}


Make s an enum and it'll work. As it is, it's a local variable created at
runtime rather than a constant at compile-time. So, use

enum s = State(adf);


- Jonathan M Davis


Thanks

worked


Re: Best practice and module declarations

2010-07-15 Thread Rory McGuire
On Thu, 15 Jul 2010 00:22:34 +0200, Jonathan M Davis  
jmdavisp...@gmail.com wrote:


I was wondering what the general consesus was (if there is one) on  
whether it's

valuable to always put module declarations in each module.

Obviously, if you need the module to have a name other than the file  
name, then
you need to have the module declaration. However, is it necessarily  
desirable to
have it when the module name matches the file name? Or would there even  
be a

reason for it to be desirable _not_ to have the module declaration?

I can't think of any particularly strong reasons to have it or not to  
have it.
My first reaction is to just always use it, but thinking about it, I'm  
not sure
that there's really much point if the file name and the module name  
already

match. Does anyone have reasons why it would matter other than personal
preference?

- Jonathan M Davis


From what I remember in TDPL:
Can be used to rename a module if you have it in a different directory  
structure than how you use it. E.g. implementation and headers in  
separate folders.

Can be used to rename module when a filename is not a valid D symbol.

-Rory


Re: Best practice and module declarations

2010-07-15 Thread Rory McGuire

On Thu, 15 Jul 2010 23:08:07 +0200, torhu n...@spam.invalid wrote:


On 15.07.2010 21:59, Rory McGuire wrote:

  From what I remember in TDPL:
Can be used to rename a module if you have it in a different directory
structure than how you use it. E.g. implementation and headers in
separate folders.


If you use *.di files (headers), you would normally just keep the  
directory structure, but put the whole thing in a different root  
directory.  Just having *.d and *.di files in the same directory works  
too, as the compiler prefers the *.di files.



Andrei's use case was if you had multiple teams of programmers with some  
allowed to work on

interfaces and others only allowed to work on the implementations.




Can be used to rename module when a filename is not a valid D symbol.


That would fool the D-specific build tools, and DMD itself too.  In most  
cases it's easier to just rename the file too.  It can be made to work  
using a *.di file if you really have to.


Andrei's example had hyphens in the file name, sometimes policy comes  
first? yes no. Not that I
can think of a reason for the policy off hand perhaps GTK naming  
convention.


Re: Recommended way to do RAII cleanly

2010-07-12 Thread Rory McGuire
On Mon, 12 Jul 2010 08:25:32 +0200, Jonathan M Davis  
jmdavisp...@gmail.com wrote:


Okay. There are cases where you want a constructor to do something when  
the
class/struct is created, and you want the destructor to do something  
when the
class/struct goes out of scope. A classic example would be an autolock  
for a
mutex. Another would be the hourglass in MFC - it's displayed when the  
object is
created and disappears when the object is destroyed (so all you have to  
do is
declare the object it at the beggining of the function and it  
automatically is

displayed and then disappears). This is classic RAII.

Obviously, because classes are reference types with infinite lifetime  
while
structs are value types with their lifetime restricted to their scope,  
structs
would be the better choice for RAII. I have noticed a bit of a snag  
however:

structs can't have default constructors.

After reading TDPL, I completely understand that structs can't have  
default
constructors due to how the init property works. However, the classic  
case where
you want to simply declare an object and have it do what it does through  
RAII

then falls apart. Ideally, you'd have something like this

struct S
{
this()
{
/* do something */
}

~this()
{
   /* undo what you did before or do whatever clean up is required  
for it */

}
}

void main()
{
auto s = S();
   /* whatever the rest of main() does */
}


Thanks to the lack of default constructor, you can't do that. Therefore,  
I see 2

options:

1.  Create a nonsensical constructor that takes an argument of _some_  
kind which

is totally ignored.

2. Create a factory function to create the struct, and it does whatever  
would

have been in the default constructor.


Out of those two options, the second seems the best, but it seems to me  
that
there have got to be more options than that. So, the question is what  
would be
the best option (be it one of those or another that I haven't though of)  
to do
RAII in the general case? What would be best practice for D when  
dealing with
structs intended for RAII without any arguments to their constructor  
when you

can't have a default constructor?

- Jonathan M Davis


Do you know about the scope storage class, or about scope classes?

{
scope tmp = new A();

// use tmp;

tmp destructor is called.
}

scope classes are similar:
http://www.digitalmars.com/d/2.0/class.html


Re: std.pattern.. templated publisher subscriber pattern, adding events to collections

2010-07-07 Thread Rory McGuire

On Wed, 07 Jul 2010 00:47:32 +0200, BLS windev...@hotmail.de wrote:

Okay a  bit better snippet than before. snippet should be almost  
functional..


/*
Hi,
Andrei brings in the idea of std.pattern. Seems that this module is
stalled;  Unfortunately !
However I would like to enhance collection classes (likewise
dcollections)  with a Publisher - Subscriber pattern (signal - slot, or
observer pattern) , if you prefer)
Hope the idea of enhancing collections with events become clear with the
following snippet.
!!! I am able to spend just a few hours a month with D programming.. in
other words, please don't kill me :)
Untested Draft code which requires a lot of help and ,more important,
feedback from you.

*/

struct publisherMsg(T) {
T data;
Action a;
}

mixin template Publisher(T) {
private :

enum Action = {INSERT, UPDATE, DELETE, READONLY};   
//alias typeof(this) PT;

struct receiver {
Object o;
callback cb;
}

receiver[] subscriber;

publisherMsg!(T) msg;

alias void delegate(const ref msg) callback;

void addSubscriber(object o, callback cb) {
//subscriber ~= o;
}   

void publish() {
foreach  (object o ; subscriber)
{
// create message and send message

}
}   
}

mixin template Subscriber() {
   // see UndoList for implementation   
}

final class Stack(T, bool observable = false ) {
T[] data;   

static if (observable)  mixin Observable!T;

void push( T t) {
data ~= t;
publish(t, Action.INSERT);  
}
T pop() {
publish(t, Action.DELETE);
//...
}   
bool empty() {

}
T top() {
publish(t, Action.READONLY);
//...
}
size_t size() {

}
}
// Undo list will receive every pushed or popped item -data and action)
class UndoList(T) {
private:
T[] data;

/// should be part of the sunscriber mixin templates.
publisherMsg!T stackMessage;

void delegate(const ref stackMessage) dg;

alias Stack!(int) IntegerStack;

IntegerStack intstack = new IntegerStack;

private this() {
dg = this.feedback;

// SUBBSCRIBE Stack(T) push and pop events.
intstack.addSubscriber(this, dg);

}
public void feedback(const ref stackMessage msg ) {
writefln(Action);
}
}


Hi Bjoern,

your mixin template should have private { ... } rather than private: I  
believe the current way will make

everything that uses the mixin template private after its used.


Re: Grokking std.container and Ranges

2010-06-29 Thread Rory McGuire

On Tue, 29 Jun 2010 07:16:13 +0200, BCS n...@anon.com wrote:


Hello Mike,


I want to do the following:
foreach(obj; list)
{
if(obj.pleaseKillMe)
somehow_remove_the_object_from_the_list();
}


That isn't legal for normal arrays or AAs. IIRC the docs even say that  
you can't change what a foreach is iterating over during the foreach. I  
think you will have to convert to a manual for loop to make it work.  
That said, I've not worked with range at all.




Perhaps keep the foreach and make a list of to be deleted objects and then  
delete them after the foreach.


Re: @property and interfaces

2010-06-29 Thread Rory McGuire

On Tue, 29 Jun 2010 14:42:33 +0200, BLS windev...@hotmail.de wrote:


Hi bearophile,
sorry for my ignorance, but what is the difference between @disable and  
simply deleting the line ?

where can I read more about @disable ?
thanks, bjoern


@disable propagates throughout the objects hierarchy (all children).

you can use it to disable builtins as well such as opEquals


Re: A module comprehensive template-specialization

2010-06-28 Thread Rory McGuire
On Mon, 28 Jun 2010 11:09:13 +0200, Matthias Walter  
xa...@xammy.homelinux.net wrote:



On 06/28/2010 09:49 AM, Justin Spahr-Summers wrote:

On Sun, 27 Jun 2010 18:51:35 +0200, Matthias Walter
xa...@xammy.homelinux.net wrote:


Hi list,

I tried to write a traits class comparable to iterator_traits in C++  
STL
or graph_traits in Boost Graph Library in D 2.0, but failed to do so  
via

template specialization which is put into different modules. Putting
everything into one module interferes with extensibility. I tried the
following:

== Module a ==
| module a;
|
| template Base (T)
| {
|   alias T Base;
| }

== Module b ==
| module b;
|
| import a;
|
| template Base(T: T*)
| {
|   alias Base !(T) Base;
| }

== Main module ==
|
|  import a, b;
|
| int main(char[][] args)
| {
|   alias Base !(int*) foo;
|
|   return 0;
| }

The error message is:
bug.d(8): Error: template instance ambiguous template declaration
b.Base(T : T*) and a.Base(T)

Can I handle this in another way (like making the template a  
conditional

one)?

best regards
Matthias Walter


I believe this is intended behavior, as it prevents template hijacking
and the like. Using alias to import the two templates into the same
scope might help, though I'm not sure exactly how it should be done.


I tried to do so in some variants but did not succeed unfortunately. If
you have a precise idea, please let me know!



On another note, though, have you looked at __traits() and std.traits?


I looked at them but didn't find them helpful for this precise problem.
The whole reason for doing this is to make it possible to make another
existing class model the concept (i.e. have some aliases / typedefs
done) of my library class without editing any of them. As I mentioned in
my other response, a prominent example for Boost Graph
Library is the LEDA graph class, which can be enabled to be used by BGL
by more or less just specializing the graph_traits template. I'd like to
have this kind of technique available, too.

Any further suggestions?


I haven't looked at the boost stuff you mention but is it possible that  
using alias this, solves a similar or the same problem?
TDPL addresses the use of aliasing to bring multiple declarations into the  
same scope/module but it only uses actual functions not templates.


Re: auto functions not authorized inside main?

2010-06-28 Thread Rory McGuire
On Sun, 27 Jun 2010 17:17:25 +0200, Philippe Sigaud  
philippe.sig...@gmail.com wrote:


Is it defined somewhere that auto functions are not authorized inside  
main?


void main()
{
auto fun(string s) { return s;} // this does not compile
}

error:

main.d|6|found 's' when expecting ')'|
main.d|6|semicolon expected, not ')'|
main.d|6|found ')' instead of statement|
main.d|7|unrecognized declaration|
||=== Build finished: 4 errors, 0 warnings ===|


So it's not even parsed?

I couldn't find a bugzilla entry for this and I cannot believe no one  
ever

tried to put an auto fun inside main!

Is that part of the spec?

Philippe


Hope this isn't a stupid question, but how would you access this function  
if it did work?

Would it be fun(asdf)?
Is this just shorthand for:
auto fun = function(string s) {return s;};



-Rory


Re: auto functions not authorized inside main?

2010-06-28 Thread Rory McGuire



On Mon, 28 Jun 2010 16:07:43 +0200, Philippe Sigaud philippe.sig...@gmail.com wrote:On Mon, Jun 28, 2010 at 15:40, Rory McGuire rmcgu...@neonova.co.za wrote:

void main()
{
    auto fun(string s) { return s;} // this does not compile
}

Hope this isn't a stupid question, but how would you access this function if it did work?
Would it be fun("asdf")?Yes, that's what I had in mind. Basically, just using it as any other auto inner function. void main(){auto fun(string s) { return s;}auto s = fun("abc");
auto t = fun("def");} 
Is this just shorthand for:
auto fun = function(string s) {return s;};That'd be about the same, yes. Fact is, I don't really _need_ this, I was just astonished to be bitten by this.Why can I do
void main(){    string foo(string s) { return s;}}and notvoid main(){    auto foo(string s) { return s;}} ?***OK, I tested it some more, and it seems you cannot define auto function inside any other function. So auto function cannot be inner functions. I'm quite astonished I never did that when using D, but OK.
I filed a bug report, at least to update the docs. It's bug #4401.Philippe
Right! I get what you're saying, didn't realise because it was formatted more how I would format a anon delegate.You're saying "surely the compiler can infer the return type for a inner function just as much as it can infer the return type of a normal function..Must be a compiler bug.-Rory

Re: auto functions not authorized inside main?

2010-06-28 Thread Rory McGuire

On Mon, 28 Jun 2010 16:01:46 +0200, BCS n...@anon.com wrote:


Hello Rory,


On Sun, 27 Jun 2010 17:17:25 +0200, Philippe Sigaud
philippe.sig...@gmail.com wrote:


void main()
{
auto fun(string s) { return s;} // this does not compile
}


Hope this isn't a stupid question, but how would you access this
function
if it did work?
Would it be fun(asdf)?
Is this just shorthand for:
auto fun = function(string s) {return s;};


I would look almost the same to the user but should in fact be a normal  
local function.




Ye I got it now.

My brain was interpreting it as a delegate that wasn't being assigned to  
anything for some reason.


Now I get that it is just return type inferance doesn't work for inner  
functions.


-Rory


Re: @porperty problem..

2010-06-28 Thread Rory McGuire

On Mon, 28 Jun 2010 22:37:06 +0200, BLS windev...@hotmail.de wrote:


Hi I have a forward reference pb in conjunction with @property.
Err msg is :
forward refrence to inferred return type of function call s1.servername.
any ideas ? beside, where are the @property docs ?
thanks, bjoern

final class LoadBalancer {
private static LoadBalancer lb;
private Server[] servers;

static this() {
synchronized lb = new LoadBalancer;
}

private this() {
Server s1 = new Server();
s1.servername = Server 1;  // ERROR
servers ~= s1;
}

public static LoadBalancer getLoadBalancer() {
   return lb;
 }

@property nextServer() {
return servers[0];
}

class Server {
private string _name, _id;

@property servername(string name) {
_name = name;
}
@property servername() {
return _name;
}
}
}


Only place I've seen @property docs is in TDPL


Re: Cannot initialize associative array.

2010-06-23 Thread Rory McGuire

On Wed, 23 Jun 2010 00:30:40 +0200, Ali Çehreli acehr...@yahoo.com wrote:


dcoder wrote:

  So, I moved the initialization to inside the main function, and now  
it works.

  Great.  I think we need to put this question in the FAQ.

For future reference, if it really needs to be global:

uint[string] mywords;

static this()
{
 mywords = [ Hello : 1, World : 1, Cat : 1, Dog : 1 ];
}

Ali




from what I have read in TDPL so far (about half way now), there is no  
mention of this limitation.

It just says that [key:value] is how you would statically initialize a AA.

Does this mean that it is just a D implementation issue. To me its seems  
like this should be a defined part
of the language. Also the compiler should really rewrite it to your above  
code anyway, surely?


-Rory


Re: Tempated class instantiation

2009-12-16 Thread Rory McGuire
Mike L. sgtmuff...@myrealbox.com wrote:
 
 Simen kjaeraas Wrote:
 
 On Wed, 16 Dec 2009 07:25:39 +0100, Mike L. sgtmuff...@myrealbox.com  
 wrote:
 
  I'm making a class template that only works with strings, so I thought  
  it'd be good to instantiate each template with char, wchar, and dchar  
  right in the template's module so that when it's compiled it'll be part  
  of the .obj file and won't have to compile it for every other project  
  that uses it. However, I get an error reproducible with this:
 
  module test;
 
  class A(T)
  {
   version(broken)
   {
class B
{
 T blah() { return t; }
}
   }
   
   T t;
  }
 
  mixin A!(int);
 
  int main()
  {
   A!(int) a = new A!(int)();
   return 0;
  }
 
  If what I want to do makes sense, how should I be doing it?
 
 It makes sense. Seems to be another compiler bug, but I have
 no good overview of which (might even be a new one).
 This compiles and runs:
 
 class A(T)
 {
  version(broken)
  {
  class B
  {
  // Explicitly state which t we're talking about.
  T blah() { return this.outer.t; }
  }
  }
 
  T t;
 }
 
 mixin A!(int);
 
 int main()
 {
  A!(int) a = new A!(int)();
  return 0;
 }
 
 
 -- 
 Simen
 
 Thanks for the reply, that seems to be working for my project too, but the 
code gets really ugly really fast. Should I submit a bug report?
 
 --Mike L.
 

As grauzone said, you have to use an alias, or you could use a template. but 
the 
code above just does the same old templated class instantiation, you can leave 
out the mixin A!(int); line completely.
As far as I understand it a template is always evaluated at least once for each 
type T. So perhaps if you used it in the module that declares it the compiler 
would detect that it doesn't need to compile it again but I'm not convinced of 
that because the instance is in a different module.

-Rory



Re: why can't structs implement interfaces?

2009-11-25 Thread Rory McGuire
Saaa em...@needmail.com wrote:
 
 struct S : Pos {}
 Why is this not possible? 
 
 
 

Why do you want to use a struct for that, rather than a class?



Re: reading files from a directory

2009-11-25 Thread Rory McGuire
miriac 1234...@gmail.com wrote:
 
 Jesse Phillips Wrote:
 
 miriac Wrote:
 
  I'm trying to get my program to read all the files in a directory.
  dmd gives an errer that theis imports dont exist:
   tango.io.FileSystem,
   tango.io.FileRoots,
  Can someone please help me and tell me what i use to do so?
  thanxs
  M
 
 As jcc7 mentioned it sounds like you're using a Tango example without 
installing Tango first. For more details about starting with D:
 
 http://www.prowiki.org/wiki4d/wiki.cgi?D__Tutorial/StartingWithD
 
 I really do want to stick to tongo, i instaled it with the instructions in 
 the 
tongo book but i can try downlding it again and see if it works
 thanks
 

My reply before checking the docs:

if its not working after installation then the import paths are incorrect.

you could start by checking that.

and also note that tango trunk and the latest tango release are somewhat 
different.

also it looks like you should be using trunk because the next release is due 
out 
shortly.

My reply after checking the api docs:

I don't see tango.io.FileRoots anywhere, check the version of tango you are 
trying to use.



Re: How to set non-static variable in static method within class

2009-11-20 Thread Rory McGuire
Sam Hu samhu.sa...@nospam.com wrote:
 
 Ary Borenszweig Wrote:
 
 
 You can't access non-static data from a static method. Non-static data 
 is related to an instance of a class, and a static method is not bound 
 to any instance.
 
 Why do you want to do that?
 
 Say I want to implement an utility dialog, InputDialog in DFL which is a 
subclass of Form,using its static method I can call InputDialog.getString to 
retrieve a string from the textbox of this dialog  other than create an 
instance 
of InputDialog,at the mean time I want to customize the caption text and the 
prompt message of the InputDialog in the static method 
InputDialog.getString.But 
I can't modify Form.text, (form.)TextBox.text  in the static method.Currently I 
have to  use its non-static version of getString method and create an instance 
of the dialog each time when I call getString.
 

since non-static data is only created with an instance you would have to use 
some sort of Singleton or something, I suppose.