Re: std.random question
On Sunday, 3 May 2015 at 09:04:07 UTC, tired_eyes wrote: On Sunday, 3 May 2015 at 08:48:52 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); } Not so simple, unfortunately. Actual code: import std.random; struct Mystruct { auto id = uniform(0, 10); } void main() { // wahtever } ..and no luck. I think it is a bug: import std.stdio, std.random; struct Mystruct { //mixin(`auto id = uniform(0, 10);`); // Error: static variable initialized cannot be read at compile time int val; } void main() { Mystruct test; test.val = uniform(0, 10); // OK writeln(test.val); mixin(`auto n = uniform(0, 10);`); // OK }
Re: Parameter storage class 'in' transitive like 'const'?
On Sunday, 3 May 2015 at 05:20:34 UTC, Ali Çehreli wrote: We know that 'in' is equivalent to const scope: http://dlang.org/function.html#parameters So, the constness of 'in' is transitive as well, right? Ali Of course, there's no concept of non-transitive const in D: struct S { char[] str; } void foo(in S s) { pragma(msg, typeof(s.str)); // const(char[]) }
Re: Parameter storage class 'in' transitive like 'const'?
On Saturday, May 02, 2015 22:20:33 Ali Çehreli via Digitalmars-d-learn wrote: We know that 'in' is equivalent to const scope: http://dlang.org/function.html#parameters So, the constness of 'in' is transitive as well, right? Of course. in is identical to const scope. It doesn't introduce anything new. It's basically just an alias. And I really wish that folks would stop using it, since it implies scope, and scope hasn't been properly implemented or even designed out yet... - Jonathan M Davis
std.random question
Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64
Re: std.random question
On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); }
Re: std.random question
On Sunday, 3 May 2015 at 08:48:52 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); } Not so simple, unfortunately. Actual code: import std.random; struct Mystruct { auto id = uniform(0, 10); } void main() { // wahtever } ..and no luck.
Re: UDA and ReturnType!(__traits...) doesn't work
On Sunday, 3 May 2015 at 17:22:00 UTC, filcuc wrote: Hi all, i'm working in the generation of the code but i'm failing in extracting a function return type when invoking the ReturnType!(T) type trait and mixing it with __traits(getMember) function. Can anyone help me? or explaining what is happenning? i've created a gist here: https://gist.github.com/filcuc/14c3a6cac89beb69cccd The error message is the following: main.d-mixin-58(58): Error: template instance main.Person.ReturnType!(name) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d-mixin-58(58): Error: template instance std.traits.ReturnType!(Monitor) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d(73): Error: template instance main.IterateUDA!(Person) error instantiating Try adding the following around your 'string returnType = ...' code: static if(isSomeFunction!(__traits(get member, T, member)) { ... } The problem is that you're looping over all the fields in T, including the data members which obviously don't have a return type. I guess ReturnType should probably use a static assert to give a better error message.
Re: Classes. C++ to D
On Sunday, 3 May 2015 at 17:35:42 UTC, Dennis Ritchie wrote: Hi, How can I rewrite this code to the D? - #include string #include iostream class A { public: std::string a() { return std::string(foo); } }; class B { public: std::string b(){ return std::string(bar); } }; class C : public A, public B {}; int main () { C c; std::cout c.a() c.b() std::endl; return 0; } This is not really doable right now in D. You can forward the function calls to a and b easily enough, but you can't inherit from more than one class. Once the multiple alias this patch gets merged you will be able to do this in D.
Re: UDA and ReturnType!(__traits...) doesn't work
On Sun, 03 May 2015 17:21:58 +, filcuc wrote: Hi all, i'm working in the generation of the code but i'm failing in extracting a function return type when invoking the ReturnType!(T) type trait and mixing it with __traits(getMember) function. Can anyone help me? or explaining what is happenning? i've created a gist here: https://gist.github.com/filcuc/14c3a6cac89beb69cccd The error message is the following: main.d-mixin-58(58): Error: template instance main.Person.ReturnType!(name) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d-mixin-58(58): Error: template instance std.traits.ReturnType!(Monitor) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d(73): Error: template instance main.IterateUDA!(Person) error instantiating the thing is that you mixed CTFE and runtime code in a weird way. ;-) the following works: void IterateUDA(T)() { import std.typetuple : staticIndexOf; foreach (member; __traits(allMembers, T)) { // Check that the given member is a function static if (is(typeof(__traits(getMember, T, member { bool isFunction = __traits(isVirtualFunction, __traits(getMember, T, member)); if (!isFunction) continue; // Retrieve the UDA enum attributes = __traits(getAttributes, __traits(getMember, T, member)); // Extract the Function Return Type and Arguments if `Slot()` is found static if (staticIndexOf!(Slot(), attributes) = 0) { enum returnType = ReturnType!(__traits(getMember, T, member)).stringof; import std.stdio; writeln(returnType); } } } } yet i think you need to read more about CTFE and metaprogramming, to avoid mixing different code. signature.asc Description: PGP signature
Re: Classes. C++ to D
On Sunday, 3 May 2015 at 17:46:54 UTC, Meta wrote: This is not really doable right now in D. You can forward the function calls to a and b easily enough, but you can't inherit from more than one class. Once the multiple alias this patch gets merged you will be able to do this in D. On Sunday, 3 May 2015 at 18:17:26 UTC, Adam D. Ruppe wrote: I'd make class A and class B into mixin templates instead. mixin template A { string a() { return foo; } } mixin template B { string b() { return bar; } } class C { mixin A; mixin B; } If you still need class A and class B, just make a class that mixes in the template for them too. Since the C++ methods aren't virtual, I imagine you don't really need a base class for them, but if you do want a virtual base class, make interfaces and inherit from as many of them as you need. Thanks. On Sunday, 3 May 2015 at 20:03:00 UTC, QAston wrote: If you want to learn a language properly, translating the idioms directly from what you already know is a bad approach. You're going to be frustrated that something was easy (to you) in your old language and the new one is weird and different than the old one. Also - results are often suboptimal. I've seen this happen too many times to not warn you, but if you just want to carry over and you don't care about learning or quality of result then please carry on. At the moment, I do not do a complete study of the D, so the quality is not important to me. Start a complete study of D, I plan a little later.
CTFE template predicates
Hi, I have now played a around couple of hours (reading everything I could find) to get something to work, but I think I'm missing some basic concepts/understanding. Maybe someone can enlighten me how these things work. I thought that some code from David Nadlinger is what I'm searching for but don't know how to exactly make use of it. Here is the code: I want to filter out some of the allMembers and use them in my code for a switch/final to check that call cases that were not filtered are covered. Trying to build the enum for the switch/final statement. auto org_rules = TypeTuple!(__traits(allMembers,BolSource)); static assert(!isTypeTuple!(org_rules)); template startsNotWith(T,char C){ static if (T[0] != C){ enum startsNotWith = true; } else { enum startsNotWith = false; } } template StaticFilter(alias pred, T...) { static if (T.length == 0) { alias TypeTuple!() StaticFilter; } else static if (pred!(T[0])) { alias TypeTuple!(T[0], StaticFilter!(pred, T[1 .. $])) StaticFilter; } else { alias StaticFilter!(pred, T[1 .. $]) StaticFilter; } } alias startsNotWithp = startsNotWith!(T,p); // doesn't compile: Error: undefined identifier T alias rules = StaticFilter!(startsNotWithp, org_rules); While playing with this a couple of questions came up: 1. How do predicates get their argument(s)? I saw code where only the predicate was mentioned but no arguments. So, I assume there is some behind-the-curtain-magic going on. I read about things like a == b where I can reference 'a and 'b in a string. 2. enum startsNotwith = false So this is the return syntax for a CTFE for return(true) ? 3. TupleType is a very missleading name when you are learning these things, because the tuple can hold values as well. Or is there a more extensive explanation for the name I don't get? 4. Are there any tutorials about CTFE? This seems to be a very powerful but not so easy to use feature of D, but documentation is quite limited. Thanks a lot. -- Robert M. Münch http://www.saphirion.com smarter | better | faster
Re: CTFE template predicates
On Sunday, 3 May 2015 at 21:46:11 UTC, Robert M. Münch wrote: Hi, I have now played a around couple of hours (reading everything I could find) to get something to work, but I think I'm missing some basic concepts/understanding. Maybe someone can enlighten me how these things work. I thought that some code from David Nadlinger is what I'm searching for but don't know how to exactly make use of it. Here is the code: I want to filter out some of the allMembers and use them in my code for a switch/final to check that call cases that were not filtered are covered. Trying to build the enum for the switch/final statement. auto org_rules = TypeTuple!(__traits(allMembers,BolSource)); static assert(!isTypeTuple!(org_rules)); template startsNotWith(T,char C){ static if (T[0] != C){ enum startsNotWith = true; } else { enum startsNotWith = false; } } Here T would have to be a type. But you want to accept a string. So: template startsNotWith(string s,char c){ enum startsNotWith = s.length == 0 || s[0] != c; } template StaticFilter(alias pred, T...) { static if (T.length == 0) { alias TypeTuple!() StaticFilter; } else static if (pred!(T[0])) { alias TypeTuple!(T[0], StaticFilter!(pred, T[1 .. $])) StaticFilter; } else { alias StaticFilter!(pred, T[1 .. $]) StaticFilter; } } alias startsNotWithp = startsNotWith!(T,p); // doesn't compile: Error: undefined identifier T You need to turn T into a parameter, so that StaticFilter can set it. (And it's really a string again, so I'm renaming to s.) template startsNotWithp(string s) { enum startsNotWithp = startsNotWith!(s, 'p'); } /* Shorthand syntax: enum startsNotWithp(string s) = startsNotWith!(s, 'p'); */ alias rules = StaticFilter!(startsNotWithp, org_rules); While playing with this a couple of questions came up: 1. How do predicates get their argument(s)? I saw code where only the predicate was mentioned but no arguments. So, I assume there is some behind-the-curtain-magic going on. I read about things like a == b where I can reference 'a and 'b in a string. Predicates are called/instantiated by the thing to which you pass them. StaticFilter instantiates pred for each element of the T tuple it's given. If some documentation doesn't say how the predicate will be called/instantiated, then it's probably assumed to be obvious. String predicates are turned into functions behind the curtains. The thing you instantiate with a == b turns it into `(a, b) {return a == b;}` and uses that. I think we don't do string predicates for templates like StaticFilter, though. 2. enum startsNotwith = false So this is the return syntax for a CTFE for return(true) ? It's the template syntax for return false. CTFE does normal functions at compile time, so there it's just return false. /* Template: */ template t() {enum t = false;} enum x = t!(); /* CTFE: */ bool f() {return false;} enum y = f(); 3. TupleType is a very missleading name when you are learning these things, because the tuple can hold values as well. Yup. And std.traits.isTypeTuple only adds to the confusion. Or is there a more extensive explanation for the name I don't get? Not that I'm aware of. 4. Are there any tutorials about CTFE? This seems to be a very powerful but not so easy to use feature of D, but documentation is quite limited. CTFE is rather simple. It just allows you to use certain functions in a static (i.e. compile time) context. Templates are more tricky. If you mean templates, maybe having the right name helps.
Re: CTFE template predicates
On Sunday, 3 May 2015 at 21:46:11 UTC, Robert M. Münch wrote: 3. TupleType is a very missleading name when you are learning these things, because the tuple can hold values as well. Or is there a more extensive explanation for the name I don't get? Legacy we are trying to get rid of. See also: https://github.com/D-Programming-Language/phobos/pull/3128 https://github.com/D-Programming-Language/dlang.org/pull/986
Is this expected? default to public members in private class
It seems a private class or struct defaults to public members. Just curious if this is intended. I would have expected private all the way down unless overriden. --- plugh.d module plugh; auto makeFoo() {return new Foo;} private: class Foo { void maybepriv() {} private void priv() {} public void pub() {} } --- xyzzy.d module xyzzy; import plugh; void main() { auto f = makeFoo(); f.maybepriv(); // is accessible after all //f.priv(); // err expected, member private f.pub(); } -- Dan Olson
Struct lifetime wrt function return?
I remember reading that guaranteed RVO was part of the D standard, but I am completely unable to find anything on it in the specification. I'm also unable to find anything in it that explicitly states the lifetime of returning a stack-local struct from a function. However, it does state Destructors are called when an object goes out of scope. So without guaranteed RVO I am quite confused. I apologize because this code will likely be poorly formatted. import std.stdio; struct S{ ~this(){ writeln(Goodbye!); } } S foo(){ S s; return s; } void main() { S s2 = foo(); } This says Goodbye! exactly once, indicating(?) that S was NRVO'd which means the scope of s went from foo to main. However, is this a guarantee by the standard? Is an implementation allowed to define foo such that it returns by copy and calls a destructor on s, meaning Goodbye! would print out twice?
Converting (casting?) a dynamic array to a fixed array?
This following code works fine. A triangle is displayed. GLfloat[6] verts = [ 0.0, 1.0, -1.0, -1.0, 1.0, -1.0 ]; glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // Some of the types are: glBufferData(GL_ARRAY_BUFFER, verts.sizeof, verts, GL_STATIC_DRAW); Then, all I do is take out the 6 so that the static array becomes a dynamic one. It compiles fine. GLfloat[] verts = [ 0.0, 1.0, -1.0, -1.0, 1.0, -1.0 ]; However, when I run it, the triangle disappears. According to OpenGL, glBufferData shows: void glBufferData( ignore, GLsizeiptr size, const GLvoid * data, ignore); So I thought the best solution would be to simply cast the dynamic array to a pointer? So I tried: glBufferData(GL_ARRAY_BUFFER, verts.sizeof, cast(const GLvoid *) verts, GL_STATIC_DRAW); and glBufferData(GL_ARRAY_BUFFER, verts.sizeof, cast(const GLvoid *) verts, GL_STATIC_DRAW); and glBufferData(GL_ARRAY_BUFFER, verts.sizeof, verts.ptr, GL_STATIC_DRAW); and glBufferData(GL_ARRAY_BUFFER, verts.sizeof, cast(const GLvoid *) verts.ptr, GL_STATIC_DRAW); and nothing but more blank screens. Any ideas? Thanks.
Re: Converting (casting?) a dynamic array to a fixed array?
On Monday, 4 May 2015 at 02:47:24 UTC, WhatMeWorry wrote: glBufferData(GL_ARRAY_BUFFER, verts.sizeof, verts, GL_STATIC_DRAW); Try (GL_ARRAY_BUFFER, verts.length, verts.ptr, GL_STATIC_DRAW) or maybe: (GL_ARRAY_BUFFER, verts.length * verts[0].sizeof, verts.ptr, GL_STATIC_DRAW) I'm not sure exactly what the function needs, but using the .length and .ptr properties on a dynamic array will probably work better than casting, and definitely work better than casting the address of it. (A dynamic array is actually a struct { size_t length; T* ptr; } object instead of raw memory like a static array, so taking the address of it actually gives the address of that length variable, not the data. the ptr attribute gets the pointer to the data. BTW static arrays also have .length and .ptr properties you can use the same way.)
Re: Converting (casting?) a dynamic array to a fixed array?
On Monday, 4 May 2015 at 02:47:24 UTC, WhatMeWorry wrote: This following code works fine. A triangle is displayed. GLfloat[6] verts = [ 0.0, 1.0, -1.0, -1.0, 1.0, -1.0 ]; glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); // Some of the types are: glBufferData(GL_ARRAY_BUFFER, verts.sizeof, verts, GL_STATIC_DRAW); Then, all I do is take out the 6 so that the static array becomes a dynamic one. It compiles fine. GLfloat[] verts = [ 0.0, 1.0, -1.0, -1.0, 1.0, -1.0 ]; However, when I run it, the triangle disappears. According to OpenGL, glBufferData shows: void glBufferData( ignore, GLsizeiptr size, const GLvoid * data, ignore); So I thought the best solution would be to simply cast the dynamic array to a pointer? So I tried: glBufferData(GL_ARRAY_BUFFER, verts.sizeof, cast(const GLvoid *) verts, GL_STATIC_DRAW); and glBufferData(GL_ARRAY_BUFFER, verts.sizeof, cast(const GLvoid *) verts, GL_STATIC_DRAW); and glBufferData(GL_ARRAY_BUFFER, verts.sizeof, verts.ptr, GL_STATIC_DRAW); and glBufferData(GL_ARRAY_BUFFER, verts.sizeof, cast(const GLvoid *) verts.ptr, GL_STATIC_DRAW); and nothing but more blank screens. Any ideas? Thanks. sizeof on a slice doesn't do what you think it does, it returns the size of the actual slice object I believe.
Re: Efficiently passing structs
On Sunday, May 03, 2015 21:58:12 bitwise via Digitalmars-d-learn wrote: If I have a large struct that needs to be passed around, like a 4x4 matrix for example, how do I do that efficiently in D? In std.datetime, in is used for most struct parameters, but I'm confused by the docs for function parameter storage classes[1]. In C++, I would pass a large struct as (const): void foo(const Matrix4x4 m); Is in in D the same as passing by const in C++? The documentation doesn't say anything about in being a reference, but it doesn't say that out parameters are references either, even though it's usage in the example clearly shows that it is. Thanks, Bit http://dlang.org/function.html#parameters std.datetime's use of in is pointless and really should be removed. I misunderstood it at the time I did that. in is essentially an alias for const scope, and scope does nothing in most cases, basically making it const, which is generally pointless for a function parameter unless you're specifically trying to make it so that it can't be mutated inside the function. And since scope has not even been properly designed (let alone implemented), I would argue that using in is almost always a bad idea. The equivalent to const in D is const ref except that it does not accept rvalues. So, if you want to be able to do the same, you'll have to do something like void foo(ref const Matrix4x4 m) { ... } void foo(const Matrix4x4 m) { foo(m); } D will move the argument if it can rather than copying it (e.g. if a temporary is being passed in), which reduces the need for worrying about copying like you tend to have to do in C++98, and I think that a lot of D code just doesn't worry about the cost of copying structs. However, if you have a large object that you know is going to be expensive to copy, you're either going to have to use const ref (and thus probably duplicate the function to allow rvalues), or you're going to need to make it a reference type rather than having all of its data live on the stack (either by making it so that the struct contains a pointer to its data or by making it a class). In general, if you're dealing with a type that is going to be expensive to copy, I'd advise making it a reference type over relying on const ref simply because it's less error-prone that way. It's trivial to forget to use ref on a parameter, and generic code won't use it, so it'll generally work better to just make it a reference type. - Jonathan M Davis
Re: What wrong?
On Saturday, 2 May 2015 at 20:46:32 UTC, Dennis Ritchie wrote: On Saturday, 2 May 2015 at 19:38:01 UTC, Fyodor Ustinov wrote: I see it by the lack of 42. :) But why is this receive breaks down? Report, please, about it (D)evepopers :) https://issues.dlang.org/ I'm not sure that it's not my fault. So I hope that will come by knowledgeable people and say Hey, buddy, your mistake is... :)
Re: Efficiently passing structs
On Monday, 4 May 2015 at 01:58:12 UTC, bitwise wrote: The documentation doesn't say anything about in being a reference, but it doesn't say that out parameters are references either, even though it's usage in the example clearly shows that it is. Thanks, Bit http://dlang.org/function.html#parameters it's specified in http://dlang.org/abi.html (at the bottom): out and ref are passed as pointers. The logic seems to be that if it's not specified then it's copied. Maybe `const ref` is what you're looking for...passed as pointer but the compiler will prevent writing the parameter, though it's still possible to take the address and to modify the param if the function is not @safe.
Re: Struct lifetime wrt function return?
On Mon, 04 May 2015 02:29:19 +, rsw0x wrote: This says Goodbye! exactly once, indicating(?) that S was NRVO'd which means the scope of s went from foo to main. However, is this a guarantee by the standard? Is an implementation allowed to define foo such that it returns by copy and calls a destructor on s, meaning Goodbye! would print out twice? actually, you'd better avoid code that makes assumptions about struct copying/moving. compiler is free to do what it sees better. moreover, phobos can use moving too. but it also can use copy/destroy. what i want to say is that you should write your code with structure copying in mind. remember that structure is value type, it can be freely moved and copied. you can also explicitly disable structure copying with @disable this (this); and if you concerned about code optimisation... well, NRVO is guaranteed in DMD, and recent GDC got it too. don't know about LDC, though, but you can expect that NRVO is guaranteed, yes. if new compiler will appear (SDC, for example), i think that it will do NRVO too (sooner or later). signature.asc Description: PGP signature
Re: Is it safe to reset HOLD fiber?
On Sunday, 3 May 2015 at 14:36:04 UTC, Martin Nowak wrote: On Sunday, 3 May 2015 at 12:33:36 UTC, Dzugaru wrote: Actually the documentation answers your question, please help to improve it if you don't find it clear enough. http://dlang.org/phobos/core_thread.html#.Fiber.reset Created a pull request with your answer added to a Fiber reset method description. In my opinion it should be either disallowed to reset the fiber in a HOLD state or clearly documented that stack wont be cleaned. I'm dreaded to think about random crashes in my app some hours after launch because of fiber reusing. Also, I'm not familiar with contract programming, but shouldn't the in body clause be included in all overloads of a reset, not just first? Now I'm thinking about how to do unfinished fiber reusing properly. Adding if(!isFibTerminated) return; after every Fiber.yield() is not good :(
Re: Efficiently passing structs
On Monday, 4 May 2015 at 03:57:04 UTC, bitwise wrote: I'll probably go with in ref. I think escape proof is probably a good default. Not to mention, easier to type ;) FYI I'm unsure how well `scope` storage class is currently implemented because it's in a state of flux at the moment as far as I know. `in ref` still helps document your intent of the parameter however. It's hard to track this down exactly because scope has so many different meanings in D, making it difficult to search for - at least one of them has been deprecated.
Re: A slice can lose capacity simply by calling a function
On Sunday, May 03, 2015 15:21:15 Andrew Godfrey via Digitalmars-d-learn wrote: I really don't think that it's an issue in general, but if you do want to guarantee that nothing affects the capacity of your array, then you're going to need to either wrap all access to it I agree with everything Jonathan said in both threads EXCEPT that this is not an issue. The syntax slice.capacity gives the impression that 'capacity' is a property of the slice. Such lack of consistency is a SERIOUS issue for D, especially when it occurs in something as basic as an array. I really don't see the problem. It's a natural side effect of how dynamic arrays work in D. The only thing I can see that could be changed without losing some of the capabilities that we currently have is if capacity were explicitly a separate function - e.g. calcArrayCapacity - but I really don't think that that would buy us much. You'd still have to understand how D's dynamic arrays work to understand how the capacity for a dynamic array works. And most code really doesn't care about the capacity of an array. If you profile and find that appending to an array is a hot spot in your program, then you dig in and use reserve or Appender or use something other than a naked array, and you figure out what works best for your particular use case, but for most code, it just works to use ~=. And if you're concerned about reallocations even before profiling, then it's trivial to just call reserve first or to use Appender. And unless you're doing something like constantly slicing and appending to each slice (which I expect to be a rare thing to do), you're really not going to run into problems. Sure, the semantics of D's dynamic arrays take some getting used to - especially if you want to understand all of their ins and outs. But I really don't see why it's a big problem. For the most part, D's dynamic arrays just work. - Jonathan M Davis
Re: What wrong?
On Monday, 4 May 2015 at 01:03:43 UTC, Fyodor Ustinov wrote: I'm not sure that it's not my fault. So I hope that will come by knowledgeable people and say Hey, buddy, your mistake is... :) OK. But if one does not come within three days :), duplicate topic in this section: http://forum.dlang.org/group/digitalmars.D
Efficiently passing structs
If I have a large struct that needs to be passed around, like a 4x4 matrix for example, how do I do that efficiently in D? In std.datetime, in is used for most struct parameters, but I'm confused by the docs for function parameter storage classes[1]. In C++, I would pass a large struct as (const): void foo(const Matrix4x4 m); Is in in D the same as passing by const in C++? The documentation doesn't say anything about in being a reference, but it doesn't say that out parameters are references either, even though it's usage in the example clearly shows that it is. Thanks, Bit http://dlang.org/function.html#parameters
Re: Efficiently passing structs
On Monday, 4 May 2015 at 01:58:12 UTC, bitwise wrote: If I have a large struct that needs to be passed around, like a 4x4 matrix for example, how do I do that efficiently in D? In std.datetime, in is used for most struct parameters, but I'm confused by the docs for function parameter storage classes[1]. In C++, I would pass a large struct as (const): void foo(const Matrix4x4 m); Is in in D the same as passing by const in C++? The documentation doesn't say anything about in being a reference, but it doesn't say that out parameters are references either, even though it's usage in the example clearly shows that it is. Thanks, Bit http://dlang.org/function.html#parameters Use the ref storage class. You can use more than one storage class i.e, foo(in ref int x) Unless I misunderstood you.
Re: CTFE template predicates
On 4/05/2015 9:46 a.m., Robert M. Münch wrote: Hi, I have now played a around couple of hours (reading everything I could find) to get something to work, but I think I'm missing some basic concepts/understanding. Maybe someone can enlighten me how these things work. I thought that some code from David Nadlinger is what I'm searching for but don't know how to exactly make use of it. Here is the code: I want to filter out some of the allMembers and use them in my code for a switch/final to check that call cases that were not filtered are covered. Trying to build the enum for the switch/final statement. auto org_rules = TypeTuple!(__traits(allMembers,BolSource)); static assert(!isTypeTuple!(org_rules)); template startsNotWith(T,char C){ static if (T[0] != C){ enum startsNotWith = true; } else { enum startsNotWith = false; } } template StaticFilter(alias pred, T...) { static if (T.length == 0) { alias TypeTuple!() StaticFilter; } else static if (pred!(T[0])) { alias TypeTuple!(T[0], StaticFilter!(pred, T[1 .. $])) StaticFilter; } else { alias StaticFilter!(pred, T[1 .. $]) StaticFilter; } } alias startsNotWithp = startsNotWith!(T,p); // doesn't compile: Error: undefined identifier T alias rules = StaticFilter!(startsNotWithp, org_rules); While playing with this a couple of questions came up: 1. How do predicates get their argument(s)? I saw code where only the predicate was mentioned but no arguments. So, I assume there is some behind-the-curtain-magic going on. I read about things like a == b where I can reference 'a and 'b in a string. 2. enum startsNotwith = false So this is the return syntax for a CTFE for return(true) ? 3. TupleType is a very missleading name when you are learning these things, because the tuple can hold values as well. Or is there a more extensive explanation for the name I don't get? 4. Are there any tutorials about CTFE? This seems to be a very powerful but not so easy to use feature of D, but documentation is quite limited. Thanks a lot. Have you looked at my book? https://leanpub.com/ctfe
Re: Efficiently passing structs
On Sun, 03 May 2015 22:37:52 -0400, rsw0x anonym...@anonymous.com wrote: Use the ref storage class. You can use more than one storage class i.e, foo(in ref int x) Thanks, this should work. On Sun, 03 May 2015 23:29:59 -0400, Baz bb.t...@gmx.com wrote: it's specified in http://dlang.org/abi.html (at the bottom): out and ref are passed as pointers. Awesome, thanks for the link. Maybe `const ref` is what you're looking for... I'll probably go with in ref. I think escape proof is probably a good default. Not to mention, easier to type ;)
Re: Is this expected? default to public members in private class
On Sun, 03 May 2015 18:07:20 -0700, Dan Olson wrote: It seems a private class or struct defaults to public members. Just curious if this is intended. I would have expected private all the way down unless overriden. i bet it is intended. protection of struct/class members is independed of protection of struct/class itself. this is good for code consistency: no changing of outer protection flags can alter struct/class inner machinery. so if you changed your mind about protection level of some global things, you shouldn't unnecessary fix your code in completely unrelated places. signature.asc Description: PGP signature
Re: UDA and ReturnType!(__traits...) doesn't work
On Sun, 03 May 2015 18:02:37 +, filcuc wrote: Yep sorry, i'm still learning :) i'm not blaming you at all. what i mean i that i'm bad at explanations, so you'd better read one of the D books to better understand my cryptic don't do that, do this comments. ;-) signature.asc Description: PGP signature
Re: A slice can lose capacity simply by calling a function
I really don't think that it's an issue in general, but if you do want to guarantee that nothing affects the capacity of your array, then you're going to need to either wrap all access to it I agree with everything Jonathan said in both threads EXCEPT that this is not an issue. The syntax slice.capacity gives the impression that 'capacity' is a property of the slice. Such lack of consistency is a SERIOUS issue for D, especially when it occurs in something as basic as an array. One other place I see this problem is the semantics of utf8 strings. This is DEADLY for D adoption. Personally, I think I'll be trying out Rust now, and checking back on these two issues later. This makes me sad, D is so promising ... but unfortunately the high standards it sets in many areas, are completely undercut by such basic problems. I work on large systems, and I can't imagine building a large system in this state.
Re: Is it safe to reset HOLD fiber?
On Sunday, 3 May 2015 at 12:42:23 UTC, Dzugaru wrote: Just did another test and it seems its not safe at all. Reusing the fibers with reset without properly exiting the function leads to eventual stack overflow. It won't cleanup the old stack, so it may leak resources. It will properly reset the stack though, so the fiber should behave like a new one.
Re: Merging one Array with Another
On Saturday, 2 May 2015 at 04:08:04 UTC, Ali Çehreli wrote: Interesting idea. I have defined a simple algorithm below to see how it could work (my skipped() function instead of uniq()). That's a bit above my current D experience to decide. What about just tweaking uniq() for now to propagate SortedRange and leave the rest for later? Or will this break existing uses of uniq?
Re: std.random question
import std.random; struct Mystruct { int id; static opCall() { Mystruct s; s.id = uniform(0, 10); return s; } } void main() { auto s = Mystruct(); // whatever } --- This make sense, thant you for the explanation.
Is it safe to reset HOLD fiber?
Documentation says This fiber must be in state TERM. but in the core.thread I see In contract only on reset without parameters (bug maybe?) and with HOLD condition too: assert( m_state == State.TERM || m_state == State.HOLD ); Does that mean its ok to reset the fiber if I'm not using things like scope(exit)? I don't like adding if(fibIsDestroyed) return; snippet after each Fiber.delay() - its error-prone.
Re: Is it safe to reset HOLD fiber?
Just did another test and it seems its not safe at all. Reusing the fibers with reset without properly exiting the function leads to eventual stack overflow.
Re: std.random question
Hmmm. hap.random from http://code.dlang.org/packages/hap behaves exactly the same.
Re: Reading bzipped files
On Saturday, 2 May 2015 at 20:37:44 UTC, tom wrote: i use Stephan Schiffels code from http://forum.dlang.org/thread/djhteyhpcnaskpabx...@forum.dlang.org?page=2 See polished version at: https://github.com/nordlow/justd/blob/master/zio.d
Re: Is it safe to reset HOLD fiber?
On Sunday, 3 May 2015 at 12:33:36 UTC, Dzugaru wrote: Documentation says This fiber must be in state TERM. but in the core.thread I see In contract only on reset without parameters (bug maybe?) and with HOLD condition too: assert( m_state == State.TERM || m_state == State.HOLD ); Does that mean its ok to reset the fiber if I'm not using things like scope(exit)? I don't like adding if(fibIsDestroyed) return; snippet after each Fiber.delay() - its error-prone. Actually the documentation answers your question, please help to improve it if you don't find it clear enough. http://dlang.org/phobos/core_thread.html#.Fiber.reset
Re: Merging one Array with Another
On 05/03/2015 07:56 AM, Per =?UTF-8?B?Tm9yZGzDtnci?= per.nord...@gmail.com wrote: On Saturday, 2 May 2015 at 04:08:04 UTC, Ali Çehreli wrote: Interesting idea. I have defined a simple algorithm below to see how it could work (my skipped() function instead of uniq()). That's a bit above my current D experience to decide. What about just tweaking uniq() for now to propagate SortedRange and leave the rest for later? The implementation seems trivial to me. If others don't object, I suggest you open an enhancement request. Or will this break existing uses of uniq? Other than the fact that uniq may return SortedRange, I don't see any issue. If an existing piece of code was explicitly checking whether a certain range object was UniqResult, no code should be affected. Another possibility is to return UniqResult in both cases but expose the special SortedRange member functions on it if the input were SortedRange. (Again, trivial.) Ali
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
On Friday, 1 May 2015 at 23:22:31 UTC, Dennis Ritchie wrote: Maybe someone will show a primitive packed array. I really can not imagine how to do it on D. Look at BitArray for an example https://github.com/D-Programming-Language/phobos/blob/12187d7be8b15b2f5f8ff6889cdb5ea3afb93dd1/std/bitmanip.d#L702. Here is an implementation in C++ that could be easily adopted. http://pempek.net/articles/2013/08/03/bit-packing-with-packedarray/
Re: std.random question
On Sunday, 3 May 2015 at 09:28:40 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 09:04:07 UTC, tired_eyes wrote: On Sunday, 3 May 2015 at 08:48:52 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); } Not so simple, unfortunately. Actual code: import std.random; struct Mystruct { auto id = uniform(0, 10); } void main() { // wahtever } ..and no luck. I think it is a bug: No. The aboc code defines a field of Mystruct calld 'id', with a type inferred from the static initializer expression 'uniform(0, 10)'. The problem is that a static initializer is... static! So the expression must be evaluated at compile-time. The uniform generator from std.random cannot be used at compile-time, thus the error. You could do: --- import std.random; struct Mystruct { int id; static opCall() { Mystruct s; s.id = uniform(0, 10); return s; } } void main() { auto s = Mystruct(); // whatever } ---
Re: How to I translate this C++ structure/array
On Sunday, 3 May 2015 at 02:31:51 UTC, WhatMeWorry wrote: On Saturday, 2 May 2015 at 22:36:29 UTC, anonymous wrote: [...] [1] `Vertex triangle[6]` works, but please don't do that. Thanks. I assume you would prefer I use triangle[] but with OpenGL calls the dynamic arrays don't work. But maybe that is another question for another time. No no, Vertex[6] as a type is fine. It's about where you put that [6]: Vertex[6] triangle; /* D style - yay */ Vertex triangle[6]; /* C style - boo */
Re: How to I translate this C++ structure/array
On Sunday, 3 May 2015 at 10:56:44 UTC, anonymous wrote: On Sunday, 3 May 2015 at 02:31:51 UTC, WhatMeWorry wrote: On Saturday, 2 May 2015 at 22:36:29 UTC, anonymous wrote: [...] [1] `Vertex triangle[6]` works, but please don't do that. Thanks. I assume you would prefer I use triangle[] but with OpenGL calls the dynamic arrays don't work. But maybe that is another question for another time. No no, Vertex[6] as a type is fine. It's about where you put that [6]: Vertex[6] triangle; /* D style - yay */ Vertex triangle[6]; /* C style - boo */ Oh, sure. Code has been changed. Bad habits are hard to kill.
Re: How to I translate this C++ structure/array
On Sunday, 3 May 2015 at 10:56:44 UTC, anonymous wrote: On Sunday, 3 May 2015 at 02:31:51 UTC, WhatMeWorry wrote: On Saturday, 2 May 2015 at 22:36:29 UTC, anonymous wrote: [...] [1] `Vertex triangle[6]` works, but please don't do that. Thanks. I assume you would prefer I use triangle[] but with OpenGL calls the dynamic arrays don't work. But maybe that is another question for another time. No no, Vertex[6] as a type is fine. It's about where you put that [6]: Vertex[6] triangle; /* D style - yay */ Vertex triangle[6]; /* C style - boo */ Oh sure, I've changed the code. I wish D had been my first language.
Re: A slice can lose capacity simply by calling a function
On Sunday, 3 May 2015 at 15:21:17 UTC, Andrew Godfrey wrote: I really don't think that it's an issue in general, but if you do want to guarantee that nothing affects the capacity of your array, then you're going to need to either wrap all access to it I agree with everything Jonathan said in both threads EXCEPT that this is not an issue. The syntax slice.capacity gives the impression that 'capacity' is a property of the slice. Such lack of consistency is a SERIOUS issue for D, especially when it occurs in something as basic as an array. One other place I see this problem is the semantics of utf8 strings. This is DEADLY for D adoption. Personally, I think I'll be trying out Rust now, and checking back on these two issues later. This makes me sad, D is so promising ... but unfortunately the high standards it sets in many areas, are completely undercut by such basic problems. I work on large systems, and I can't imagine building a large system in this state. It is consistent if you look at it the perspective of wanting D's slices to have certain semantics while still being memory safe. It is word behavior; however, when you think about it, it is necessary if we want D's slices to have the semantics that they do while stomping memory. If you look at Go's slices, they are NOT memory safe; it's possible (and even easy) in Go to have the data in a slice change under you unexpectedly. This behavior is impossible in D as far as I know. Yes, Rust does statically guarantee this can never happen, but it also needs its complex ownership system to do that. So D is really a midway point between Go and Rust. Not unsafe, unlike Go, but with some slightly confusing behavior.
Re: Classes. C++ to D
On Sunday, 3 May 2015 at 17:35:42 UTC, Dennis Ritchie wrote: Hi, How can I rewrite this code to the D? - #include string #include iostream class A { public: std::string a() { return std::string(foo); } }; class B { public: std::string b(){ return std::string(bar); } }; class C : public A, public B {}; int main () { C c; std::cout c.a() c.b() std::endl; return 0; } If you want to learn a language properly, translating the idioms directly from what you already know is a bad approach. You're going to be frustrated that something was easy (to you) in your old language and the new one is weird and different than the old one. Also - results are often suboptimal. I've seen this happen too many times to not warn you, but if you just want to carry over and you don't care about learning or quality of result then please carry on.
Re: Ada to D - an array for storing values of each of the six bits which are sufficient
On Sunday, 3 May 2015 at 14:49:55 UTC, Martin Nowak wrote: On Friday, 1 May 2015 at 23:22:31 UTC, Dennis Ritchie wrote: Maybe someone will show a primitive packed array. I really can not imagine how to do it on D. Look at BitArray for an example https://github.com/D-Programming-Language/phobos/blob/12187d7be8b15b2f5f8ff6889cdb5ea3afb93dd1/std/bitmanip.d#L702. Here is an implementation in C++ that could be easily adopted. http://pempek.net/articles/2013/08/03/bit-packing-with-packedarray/ Thank you. This should help.
Re: UDA and ReturnType!(__traits...) doesn't work
On Sunday, 3 May 2015 at 17:48:55 UTC, ketmar wrote: On Sun, 03 May 2015 17:21:58 +, filcuc wrote: Hi all, i'm working in the generation of the code but i'm failing in extracting a function return type when invoking the ReturnType!(T) type trait and mixing it with __traits(getMember) function. Can anyone help me? or explaining what is happenning? i've created a gist here: https://gist.github.com/filcuc/14c3a6cac89beb69cccd The error message is the following: main.d-mixin-58(58): Error: template instance main.Person.ReturnType!(name) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d-mixin-58(58): Error: template instance std.traits.ReturnType!(Monitor) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d(73): Error: template instance main.IterateUDA!(Person) error instantiating the thing is that you mixed CTFE and runtime code in a weird way. ;-) the following works: void IterateUDA(T)() { import std.typetuple : staticIndexOf; foreach (member; __traits(allMembers, T)) { // Check that the given member is a function static if (is(typeof(__traits(getMember, T, member { bool isFunction = __traits(isVirtualFunction, __traits(getMember, T, member)); if (!isFunction) continue; // Retrieve the UDA enum attributes = __traits(getAttributes, __traits(getMember, T, member)); // Extract the Function Return Type and Arguments if `Slot()` is found static if (staticIndexOf!(Slot(), attributes) = 0) { enum returnType = ReturnType!(__traits(getMember, T, member)).stringof; import std.stdio; writeln(returnType); } } } } yet i think you need to read more about CTFE and metaprogramming, to avoid mixing different code. Yep sorry, i'm still learning :) However thank you all for your help and the quick answer. As you suggested wrapping the body with the static if solved the problem. I've updated the gist https://gist.github.com/filcuc/14c3a6cac89beb69cccd Thanks!
Re: Classes. C++ to D
I'd make class A and class B into mixin templates instead. mixin template A { string a() { return foo; } } mixin template B { string b() { return bar; } } class C { mixin A; mixin B; } If you still need class A and class B, just make a class that mixes in the template for them too. Since the C++ methods aren't virtual, I imagine you don't really need a base class for them, but if you do want a virtual base class, make interfaces and inherit from as many of them as you need.
UDA and ReturnType!(__traits...) doesn't work
Hi all, i'm working in the generation of the code but i'm failing in extracting a function return type when invoking the ReturnType!(T) type trait and mixing it with __traits(getMember) function. Can anyone help me? or explaining what is happenning? i've created a gist here: https://gist.github.com/filcuc/14c3a6cac89beb69cccd The error message is the following: main.d-mixin-58(58): Error: template instance main.Person.ReturnType!(name) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d-mixin-58(58): Error: template instance std.traits.ReturnType!(Monitor) does not match template declaration ReturnType(func...) if (func.length == 1 isCallable!func) main.d(73): Error: template instance main.IterateUDA!(Person) error instantiating
Classes. C++ to D
Hi, How can I rewrite this code to the D? - #include string #include iostream class A { public: std::string a() { return std::string(foo); } }; class B { public: std::string b(){ return std::string(bar); } }; class C : public A, public B {}; int main () { C c; std::cout c.a() c.b() std::endl; return 0; }