Re: non-constant error for module AAs
On Mon, 24 Jan 2011 10:45:03 -0500, Andrej Mitrovic wrote: Is this a bug? import std.stdio; string[string] values = [abc:abc, def:def]; void main() { string[string] values2 = [abc:abc, def:def]; } test.d(3): Error: non-constant expression [abc:abc,def:def] What's non-constant about that expression? My guess would be that using an AA literal is just syntax sugar for calling an AA construction function, and that said function isn't CTFEable. When you specify an initial value for a global, that value must be a compile-time constant. If it's not, as in this case, the correct thing to do is to use a module constructor: string[string] values; static this() { values = [ abc:abc, def:def ]; } It is ONLY a good idea to use an enum array if you know you will be doing all lookups at compile time. If the key you're looking for is just known at run time, the AA will be constructed anew for each lookup (I think), which is hideously expensive. enum string[string] values = [ abc:def, ghi:jkl ]; // This is fine, because it is done at compile time. // It's essentially the same as: auto s = def; auto s = values[abc]; // This is a no-no, because it evaluates to something // like: auto aa = values; auto s = aa[key]; auto key = abc; auto s = values[key]; Here's an example program that demonstrates the difference. On my machine, the enum AA version takes 22x longer than the normal AA version. import std.datetime, std.stdio; enum string[string] enumAA = [ abc : abc, def : def ]; string[string] normalAA; static this() { normalAA = [ abc : abc, def : def ]; } void main() { enum max = 10_000_000; StopWatch sw; string lookup1 = abc; string lookup2 = def; sw.start(); foreach (i; 0 .. max) { auto a = enumAA[lookup1]; auto b = enumAA[lookup2]; } sw.stop(); writeln(sw.peek().seconds); sw.reset(); sw.start(); foreach (i; 0 .. max) { auto a = normalAA[lookup1]; auto b = normalAA[lookup2]; } sw.stop(); writeln(sw.peek().seconds); }
How to Mixin a Type List?
Instead of mixing in type by type, is there a way to mixin a Type Tuple? Some foreach Type mixin; Otherwise, I guess recursive templated inheritance with a single mixin at each level should to the trick? Thanks, Nick
Re: non-constant error for module AAs
On 01/25/2011 08:54 AM, bearophile wrote: Andrej Mitrovic: It's interesting that enum works but immutable doesn't. enum will do, Thanks. But there are some problems with enum AAs. Take a look at this little program: enum int[int] aa = [1:2, 3:4]; int foo(int x) { return aa[x]; } void main() {} And the asm of foo(): _D4test3fooFiZi comdat pushEAX mov ECX,offset FLAT:_D10TypeInfo_i6__initZ mov EDX,offset FLAT:_D12TypeInfo_Hii6__initZ pushEAX push4 pushECX push4 push3 push2 push1 push2 pushEDX callnear ptr __d_assocarrayliteralT add ESP,018h pushEAX callnear ptr __aaGetRvalue mov EAX,[EAX] add ESP,010h pop ECX ret Bye, bearophile IIUC, the compiler re-defines the constant (enum) AA at use point. Why? Denis -- _ vita es estrany spir.wikidot.com
Re: non-constant error for module AAs
On 01/25/2011 09:13 AM, Lars T. Kyllingstad wrote: On Mon, 24 Jan 2011 10:45:03 -0500, Andrej Mitrovic wrote: Is this a bug? import std.stdio; string[string] values = [abc:abc, def:def]; void main() { string[string] values2 = [abc:abc, def:def]; } test.d(3): Error: non-constant expression [abc:abc,def:def] What's non-constant about that expression? My guess would be that using an AA literal is just syntax sugar for calling an AA construction function, and that said function isn't CTFEable. When you specify an initial value for a global, that value must be a compile-time constant. If it's not, as in this case, the correct thing to do is to use a module constructor: string[string] values; static this() { values = [ abc:abc, def:def ]; } It is ONLY a good idea to use an enum array if you know you will be doing all lookups at compile time. If the key you're looking for is just known at run time, the AA will be constructed anew for each lookup (I think), which is hideously expensive. enum string[string] values = [ abc:def, ghi:jkl ]; // This is fine, because it is done at compile time. // It's essentially the same as: auto s = def; auto s = values[abc]; // This is a no-no, because it evaluates to something // like: auto aa = values; auto s = aa[key]; auto key = abc; auto s = values[key]; Here's an example program that demonstrates the difference. On my machine, the enum AA version takes 22x longer than the normal AA version. import std.datetime, std.stdio; enum string[string] enumAA = [ abc : abc, def : def ]; string[string] normalAA; static this() { normalAA = [ abc : abc, def : def ]; } void main() { enum max = 10_000_000; StopWatch sw; string lookup1 = abc; string lookup2 = def; sw.start(); foreach (i; 0 .. max) { auto a = enumAA[lookup1]; auto b = enumAA[lookup2]; } sw.stop(); writeln(sw.peek().seconds); sw.reset(); sw.start(); foreach (i; 0 .. max) { auto a = normalAA[lookup1]; auto b = normalAA[lookup2]; } sw.stop(); writeln(sw.peek().seconds); } Waow, thank you, Lars, /this/ is an explanation. Now, why doesn't D make an enum aa a normal variable like your normal aa (but evaluated at compile-time instead of import time)? Normal -- _ vita es estrany spir.wikidot.com
Re: concatenation
On Mon, 24 Jan 2011 18:39:39 -0500, Simen kjaeraas simen.kja...@gmail.com wrote: Ellery Newcomer ellery-newco...@utulsa.edu wrote: in the following: void main(){ char[] x; string s; string y; y = s ~ x; } tok.d(5): Error: cannot implicitly convert expression (cast(const(char)[])s ~ x) of type char[] to string why should typeof(s ~ x) == char[] ? http://d.puremagic.com/issues/show_bug.cgi?id=1654 I have since felt that the bug report I filed may be more trouble than it's worth. It makes perfect sense for strings or other arrays of non references, but it doesn't make sense for more complex types (as can be seen by the later discussions on that report). From the original issue, s ~ x is concatenating two different types, what should the result type be? Either choice is going to cause problems. The only correct choice is a polysemous type that can implicitly cast into either type on the assumption that the data is unique. This is pretty much what I wanted from the bug report, but I was very green back then, didn't know the right way to say it. If the enhancement can be implemented, I think it would help, but it would be nice to solve this problem in the general sense (not just for arrays). There was a suggestion earlier that a strong-pure function could return an implicitly castable type, but concatenating a mutable and immutable string would not be such a function. We would need some other way to mark a function. -Steve
template magic
Hello, This post is about the various roles D templates can play. I had to write a higher-order function (hof) that takes as parameter a func which itself returns any kind of type. Thus, the hof is also templated. (Below the simplest case I could find as example.) Unlike in functional style, in Phobos hof's often define their func parameter as a template parameter, not as a regular one. Following this example, I thus I ended up in something like this: P[] hof1 (P, alias f) (uint n) { // just n times f's result P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } // example parameter function: int f () { return 1; } This runs fine. A conceptual issue that itched my brain is that the type parameter P is in fact defined twice, once explicitely implicitely as f's return type. I thus re-placed f as an ordinary parameter: P[] hof2 (P) (uint n, P function () f) { // same as above P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } This runs fine as well. But, guessing that Phobos's way of placing funcs as template parameters may be due to a good reason, I tried to do the same and still avoid P beeing defined twice. Used std.traits' ReturnType! for this: auto hof3 (alias f) (uint n) { // below the magic alias ReturnType!f P; P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } As you see, this also requires using 'auto' for the hof's return type. But we can use the same magic trick there as well. Really ugly, but works: ReturnType!f[] hof4 (alias f) (uint n) { alias ReturnType!f P; P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } The latter trick also solves the case where P / ReturnType!f is needed elsewhere in the hof's signature, eg: ReturnType!f[] hof5 (alias f) (uint n, ReturnType!f p) { alias ReturnType!f P; P[] ps; foreach (i ; 0..n) ps ~= f(p); return ps; } Can you believe all of those versions work fine? See whole test code below. Now, 3 questions? 1. Is the fact that we have so many ways to define the same thing a Good Thing, according to you? 2. What is the reason for Phobos defining param funcs as template params? Efficiency? Why? 3. What is the meaning of 'alias f'? How does it work? This is a totally enigmatic feature for me. Seems it allows placing anything of any type as template param. Far more versatile than common use of templates as 'simple' generics. Note that if I remove the seemingly useless 'alias' from version 1 , I get: Error: template instance hof1!(int,f) does not match template declaration hof1(P,f) ??? (could not find any explanation on alias params anywhere -- pointers also welcome) Denis test code = import std.stdio; import std.traits; P[] hof1 (P, alias f) (uint n) { P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } P[] hof2 (P) (uint n, P function () f) { P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } auto hof3 (alias f) (uint n) { alias ReturnType!f P; P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } ReturnType!f[] hof4 (alias f) (uint n) { alias ReturnType!f P; P[] ps; foreach (i ; 0..n) ps ~= f(); return ps; } ReturnType!f[] hof5 (alias f) (uint n, ReturnType!f p) { alias ReturnType!f P; P[] ps; foreach (i ; 0..n) ps ~= f(p); return ps; } int f () { return 1; } int f2 (int i) { return i; } unittest { writeln( hof1!(int, f)(3) ); writeln( hof2!int(3, f) ); writeln( hof2(3, f) ); writeln( hof3!f(3) ); writeln( hof4!f(3) ); writeln( hof5!f2(3, 1) ); } void main () {} === -- _ vita es estrany spir.wikidot.com
template this parameters
Why do they exist and why does typeof(this) strip constness? import std.stdio; struct S { const void foo(this T)(int i) { writeln(typeid(T)); } const void bar() { writeln(typeid(typeof(this))); } } void main() { const(S) s; (s).foo(1); S s2; s2.foo(2); immutable(S) s3; s3.foo(3); s.bar(); s2.bar(); s3.bar(); } yields: const(templatethis.S) templatethis.S immutable(templatethis.S) templatethis.S templatethis.S templatethis.S
Re: template magic
On Tue, 25 Jan 2011 10:21:29 -0500, spir denis.s...@gmail.com wrote: Hello, This post is about the various roles D templates can play. I had to write a higher-order function (hof) that takes as parameter a func which itself returns any kind of type. Thus, the hof is also templated. (Below the simplest case I could find as example.) [snip] Can you believe all of those versions work fine? See whole test code below. Now, 3 questions? 1. Is the fact that we have so many ways to define the same thing a Good Thing, according to you? 2. What is the reason for Phobos defining param funcs as template params? Efficiency? Why? 3. What is the meaning of 'alias f'? How does it work? This is a totally enigmatic feature for me. Seems it allows placing anything of any type as template param. Far more versatile than common use of templates as 'simple' generics. Note that if I remove the seemingly useless 'alias' from version 1 , I get: Error: template instance hof1!(int,f) does not match template declaration hof1(P,f) ??? (could not find any explanation on alias params anywhere -- pointers also welcome) Your confusion probably stems from your lack of test cases :) aliases work as any definable symbol -- template (even uninstantiated ones!), function, delegate, symbol, struct, variable, etc. For instance, this also works (using your already-defined hof3)! void main() { int n; struct S { this(int step) {this.step = step;} int step; int opCall() {return (n = (n + step));} } S s = S(1); // step of 1 S s2 = S(2); // step of 2 auto intarr = hof3!s(5); // returns [1,2,3,4,5] auto intarr2 = hof3!s2(5); // returns [7,9,11,13,15] } Note how the alias maps to a *specific local variable* at compile-time, now that's kick ass. Alias is the coolest part of templates I've seen in D. It works for just about anything. What I'd say is to make your template definition correct is to add some constraints to ensure the functor (the alias parameter) is a callable type. auto hof3(alias f)(uint n) if (isCallable!f) -Steve
Re: template magic
2. What is the reason for Phobos defining param funcs as template params? Correct me if I'm wrong but there's no way to pass an arbitrary function to a function in a type-safe way. If you use pointers and casts you can't check if the passed function meets certain requirements (parameters, return type, attributes, etc.) 3. What is the meaning of 'alias f'? How does it work? This is a totally enigmatic feature for me. Seems it allows placing anything of any type as template param. http://digitalmars.com/d/2.0/template.html#TemplateAliasParameter It allows you to pass any D symbol. As the name already suggests, think of it as being a template-local alias to a symbol passed in the instantiation (but note that you can also pass literals as arguments to alias parameters).
Re: template this parameters
Trass3r u...@known.com wrote: Why do they exist and why does typeof(this) strip constness? Template this parameters allow for covariant return types, that's about all the use cases I've found for it. It seems like such a great thing, almost doing automatic overriding of methods in subclasses, but that's not what it does. As for typeof(this), that sounds like a bug. -- Simen
Re: template this parameters
On Tue, 25 Jan 2011 10:44:23 -0500, Trass3r u...@known.com wrote: Why do they exist It tells you the exact type of this at the call site. For const struct functions, this will tell you what the actual constness of the variable is. For classes, this may give you the derived or base class or interface so you can do more if you want. For example, you could return the derived type for chaining. and why does typeof(this) strip constness? That seems like a bug, but actually, I'd not trust typeid. typeid is actually a runtime-defined TypeInfo class, which you are calling toString on, which is not telling you exactly what the compiler thinks is the type. Try this instead: typeof(this).stringof which is the type the compiler uses. This might still return the wrong type. I seem to remember typeof(this) is handled specially, so you can use it inside static functions. You might try this: auto x = this; writeln(typeof(x).stringof); I would still say it's a bug, it's very surprising that inside a const member function, typeof(this) does not assume the const attribute. -Steve
Re: template this parameters
On Tue, 25 Jan 2011 10:58:18 -0500, Steven Schveighoffer schvei...@yahoo.com wrote: That seems like a bug, but actually, I'd not trust typeid. typeid is actually a runtime-defined TypeInfo class, which you are calling toString on, which is not telling you exactly what the compiler thinks is the type. I should clarify, it *could* be the same as what the compiler thinks, but this is not guaranteed. There have been bugs in TypeInfo.toString I believe in the past. -Steve
Re: template magic
Trass3r Wrote: 2. What is the reason for Phobos defining param funcs as template params? Correct me if I'm wrong but there's no way to pass an arbitrary function to a function in a type-safe way. If you use pointers and casts you can't check if the passed function meets certain requirements (parameters, return type, attributes, etc.) How do you not pass them in a safe manner? If you are casting things, of course you don't get type safety.
Re: template magic
Trass3r u...@known.com wrote: 2. What is the reason for Phobos defining param funcs as template params? Correct me if I'm wrong but there's no way to pass an arbitrary function to a function in a type-safe way. If you use pointers and casts you can't check if the passed function meets certain requirements (parameters, return type, attributes, etc.) It is perfectly possible to typesafely pass a function or delegate to a function: void foo( F )( F fn ) { fn(); } You can then add other things to pass parameters: void foo( F )( F fn, ParameterTypeTuple!F args ) { fn( arg ); } Of course, given a non-template function, it is impossible to safely pass a function to it. -- Simen
Re: template magic
On 01/25/2011 06:03 PM, Simen kjaeraas wrote: Of course, given a non-template function, it is impossible to safely pass a function to it. Dont you count this as typesafe function passing? void writeRounding (int function (float) roundingScheme) {...} Denis -- _ vita es estrany spir.wikidot.com
Re: template magic
How do you not pass them in a safe manner? If you are casting things, of course you don't get type safety. Yep, I was talking about non-template functions. Only way to pass an arbitrary function is via void*
shared library loader (wrapper for GetProcAddress Co)
I can't seem to find something like that in phobos. Is it missing or am I overlooking it?
Re: shared library loader (wrapper for GetProcAddress Co)
I don't think there are any, searching for GetProcAddress only returns loader.d which seems to be an old module for loading executables but probably unrelated to DLLs (?). There's dll_helper.d in druntime\src\core\ but it only has some TLS workaround features. I've found some good solutions for loading DLLs in the Derelict and DSFML projects though.
Re: C# code sample
On Mon, 24 Jan 2011 14:39:33 -0500, Simen kjaeraas simen.kja...@gmail.com wrote: pragma the_ignora...@hotmail.com wrote: Hi i come from a c# background I would like to write the following code in the according D style but i'm not sure howto do it c# code: void foo(IEnumerabledouble[] data) { foreach (var d in data) { do_some_stuff(d); } } i guess the D equivalent to IEnumerable is Range? how would it look like in D? void foo( R )( R data ) if ( isInputRange!R is( ElementType!R == double ) ) { foreach ( d; data ) { do_some_stuff( d ); } } Actually, isIterable would be more correct than isInputRange for this code example, not sure what the full code looks like. http://www.digitalmars.com/d/2.0/phobos/std_traits.html#isIterable -Steve How about simply saying: void foo(double[] data) { foreach (d; data) { do_some_stuff(d); } } all ranges are already foreachable. Regards Mandeep
Interface problems
Hi, Not a question but just raising a concern i am facing again and again. The current implementation of interfaces seem to be creating a number of problems. I am not able to: - find indexOf interface in an interface range using std.algorithm. - compare interface objects - assign interface to generic objects. Does COM support warrant so much weight so as to break the interfaces implementation from D1 and all other languages. What is the way to get this addressed (is there a possibility at all). Thanks Mandeep
Re: C# code sample
Mandeep Singh Brar Wrote: How about simply saying: void foo(double[] data) { foreach (d; data) { do_some_stuff(d); } } all ranges are already foreachable. Regards Mandeep He is iterating over a range/iterable of double[], Simen got the type check wrong, which I pointed out.
Re: template magic
spir Wrote: On 01/25/2011 06:03 PM, Simen kjaeraas wrote: Of course, given a non-template function, it is impossible to safely pass a function to it. Dont you count this as typesafe function passing? void writeRounding (int function (float) roundingScheme) {...} He means accepting any function no matter the return type or arguments. With templates you can do this and it will remain type safe, non-templates can't do this while remaining type safe. But then again you shouldn't really expect an arbitrary function to be type safe at runtime, unless of course you specify the types it must be, but then it isn't arbitrary in that context...
override '.' member access
Hello, Cannot find corresponding opSomething method, if any. (opDispatch seems to specialise for method call.) Else, how to catch obj.member? Denis -- _ vita es estrany spir.wikidot.com
Re: Interface problems
Mandeep Singh Brar: I am not able to: - find indexOf interface in an interface range using std.algorithm. I don't understand. Please explain better. - compare interface objects What kind of comparisons do you need to perform and why? - assign interface to generic objects. Why do you need to do this? Bye, bearophile
Re: override '.' member access
On Tuesday, January 25, 2011 11:33:24 spir wrote: Hello, Cannot find corresponding opSomething method, if any. (opDispatch seems to specialise for method call.) Else, how to catch obj.member? You're trying to override a member variable? Or are you trying to override the dot operator? You can't override either. You can override member _functions_. You can overload a number of operators, but not the dot operator. You can also use alias this or opDispatch to call functions that your object doesn't have, but you're still dealing with functions. It sounds like you're essentially trying to override a member variable, and you can't do that. It's just data. There's no function call. There's nothing to override. - Jonathan M Davis
Re: How to Mixin a Type List?
On Tue, Jan 25, 2011 at 12:33, Nick n...@example.com wrote: Instead of mixing in type by type, is there a way to mixin a Type Tuple? Some foreach Type mixin; Otherwise, I guess recursive templated inheritance with a single mixin at each level should to the trick? Could you give an example of type mixin? I'm not sure I understand what you're trying to do. Philippe
Re: override '.' member access
spir denis.s...@gmail.com wrote: Hello, Cannot find corresponding opSomething method, if any. (opDispatch seems to specialise for method call.) Else, how to catch obj.member? opDispatch is likely what you want. with the @property annotation, it will readily support obj.member; and obj.member = foo; syntax. -- Simen
Re: D2 and gdb
On Tue, 25 Jan 2011 15:44:59 -0500, vnm gre...@tut.by wrote: Why gdb can't show line information and why it shows symbols in mangled form ? Is this software issues or I'm doing something wrong ? AFAIK, gdb 7.2 integrated some patch for D support (including symbols demangling feature). This patch was D1 only ? I don't know anything about the symbol mangling, but the symbol of main is actually _Dmain. main() is the runtime's main which ends up calling your main function. I'm pretty sure gdb doesn't know this. Likely, the runtime is compiled without the debug flags, so you won't get any line info there. Try breaking on Dmain instead. -Steve
Re: override '.' member access
spir denis.s...@gmail.com wrote: On 01/25/2011 10:29 PM, Simen kjaeraas wrote: spir denis.s...@gmail.com wrote: Hello, Cannot find corresponding opSomething method, if any. (opDispatch seems to specialise for method call.) Else, how to catch obj.member? opDispatch is likely what you want. with the @property annotation, it will readily support obj.member; and obj.member = foo; syntax. Thank you, Simen, i'll try using opDispatch with @property. But I'm not sure how to write that concretely. My use case is of a type holding a string[AnyThing] AA called symbols. Then, I wish to map obj.id to obj.symbols[id] (hope I'm clear) I just found that it is, in fact, unpossible. That is, you can support either a = foo.id; or foo.id = a; - not both. This is caused by bug 620: http://d.puremagic.com/issues/show_bug.cgi?id=620 -- Simen
Re: Interface problems
Mandeep Singh Brar: I am not able to: - find indexOf interface in an interface range using std.algorithm. I don't understand. Please explain better. In the following snippet: Interface interfaceA{} class C:interfaceA{} class D:interfaceA{} interfaceA[] registry; register(interfaceA a) { registry ~= a; } unregister(interfaceA a) {idx = registry.indexOf(a); registry.replace(idx, idx+1, null); } In the above statement indexOf does not work. - compare interface objects What kind of comparisons do you need to perform and why? Simple comparisons like in the below snippet class A { interfaceTest myInstance; setInstance(interfaceTest interfaceInstance) { if(myInstance != interfaceInstance) //does not work { updateMyInstance; doStuff; } } } - assign interface to generic objects. Why do you need to do this? Just store various types of objects in a generic way like Object[] objects; objects ~= objA; objects~= interB and so on. I cant use Variant because interface can not be assigned to Variants and i cant use Objects too. Bye, bearophile Thanks Mandeep