Re: Catching signals with D
On 22-12-2011 23:51, Matej Nanut wrote: Hello everyone, I've been fascinated by D lately and have been using it for all my school assignments (like simple ray casting and simulated annealing). What I can't find anywhere is how to do something like signal(SIGINT, myhandler) (I'm in a Linux environment). I need this to stop the annealing process early but still keep the current best result. Is there a better way to interrupt my program? Thanks! Matej P.s. I hope I sent this to the appropriate address. :) Hi, Have you seen: https://github.com/D-Programming-Language/druntime/blob/master/src/core/sys/posix/signal.d ? - Alex
Reading about D: few questions
Hi guys! I'm mostly familiar with C (and a bit of PHP). I've stumbled upon the D language, and I must say I really like it. Now I'm reading the The D Programming Language book, and I have a couple of questions: 1. Uninitialized Arrays and GC. http://dlang.org/memory.html#uninitializedarrays It's said here ^ that: The uninitialized data that is on the stack will get scanned by the garbage collector looking for any references to allocated memory. With the given example of: byte[1024] buffer = void; So does the GC really scan this byte array? Or (sounds more logical to me) does it scan only reference types? If the latter is true, I think the example should use some kind of a pointer array. Also, in this case, I can't see why Uninitialized data can be a source of bugs and trouble, even when used correctly.? If the former is true, then, well, I'll ask more questions. 2. Setting Dynamic Array Length. http://dlang.org/arrays.html#resize A more practical approach would be to minimize the number of resizes The solution works but is not as clean as just using array ~= c; Is there any way (language, runtime, or phobos) to declare an array that would reallocate memory by chunks, which are multiple of x? 3. const and immutable. Is there any use for const when defining variables? As I see it, there is no use for using e.g. const int x;, as it can't be modified anyway; So with immutable, const is only good for reference variables that are initialized to refer to another variable (like a function const ref parameter). Am I right? 4. if (lhs != rhs)? std.algorithm has this in it's swap function. Is it different than if (lhs !is rhs)? Just wondering. 5. Align attribute. http://dlang.org/attribute.html#align struct S { align(4) byte a; // placed at offset 0 align(4) byte b; // placed at offset 1 } Explain this please. 6. Array slices manipulation. a[] += 1; works but a[]++ doesn't. Not so important but just wondering: why, and is it intended? 7. Anonymous structs. In C you can write: struct { int a; } s = {10}; printf(%d\n, s.a); In D you must declare the struct first: struct S { int a; }; S s = {10}; writeln(s.a); Why doesn't D allow anonymous structs? Best regards.
Re: Reading about D: few questions
Am 23.12.2011 16:25, schrieb Mr. Anonymous: Hi guys! I'm mostly familiar with C (and a bit of PHP). I've stumbled upon the D language, and I must say I really like it. Now I'm reading the The D Programming Language book, and I have a couple of questions: [] 3. const and immutable. Is there any use for const when defining variables? As I see it, there is no use for using e.g. const int x;, as it can't be modified anyway; So with immutable, const is only good for reference variables that are initialized to refer to another variable (like a function const ref parameter). Am I right? Right. There's no point in a const int but of course there is a big difference between const(int)* and immutable(int)*. 4. if (lhs != rhs)? std.algorithm has this in it's swap function. Is it different than if (lhs !is rhs)? Just wondering. They're not the same at all. is checks if the two operands have binary equality. To understand, you have to keep in mind that lhs and rhs are references and could refer to one and the same variable as in: int a = 0; swap(a, a); Now, if you want to know if two refs refer to the same variable, you use lhs == rhs. If want to know if two class instances are the same, you use is. If you want to know if two things (instances or anything else) are equal, you use ==. lhs == rhs (makes only sense with refs) rhs is lhs (always true, if the above is true) rhs == lhs (always true, if the above is true) import std.stdio; void f(ref int[] a, ref int[] b) { writefln(%s %s %s, a == b, a is b, a == b); } void main() { auto u = [1, 2, 3]; auto u2 = u; auto v = [1, 2, 3]; auto w = [4, 5, 6]; f(u, u); // true true true f(u, u2);// false true true f(u, v); // false false true f(u, w); // false false false } [...] Mafi
Re: Reading about D: few questions
On 23.12.2011 19:47, Ali Çehreli wrote: On 12/23/2011 07:25 AM, Mr. Anonymous wrote: I have a couple of questions: I prefer separate threads for each. :) Should I resend the questions as separate messages? 1. Uninitialized Arrays and GC. http://dlang.org/memory.html#uninitializedarrays It's said here ^ that: The uninitialized data that is on the stack will get scanned by the garbage collector looking for any references to allocated memory. With the given example of: byte[1024] buffer = void; So does the GC really scan this byte array? Or (sounds more logical to me) does it scan only reference types? I am not an expert on garbage collectors but I've never heard about differentiating the bits of data. The GC would have to need to keep meta data about every part of the allocated space as such and it would not be practical. Maybe not every part, but only reference parts. If the latter is true, I think the example should use some kind of a pointer array. Also, in this case, I can't see why Uninitialized data can be a source of bugs and trouble, even when used correctly.? I don't think that the last part is any different than the initialize all of your variables advice. The uninitialized data has come from memory that has been used earlier in the program and may have valid data (and references) to existing or already-destroyed data. Hard to debug. 2. Setting Dynamic Array Length. http://dlang.org/arrays.html#resize A more practical approach would be to minimize the number of resizes The solution works but is not as clean as just using array ~= c; Is there any way (language, runtime, or phobos) to declare an array that would reallocate memory by chunks, which are multiple of x? Array expansion is already more efficient than they look at first. This article is a good read: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle Thanks, I'll take a look. 3. const and immutable. Is there any use for const when defining variables? As I see it, there is no use for using e.g. const int x;, as it can't be modified anyway; So with immutable, const is only good for reference variables that are initialized to refer to another variable (like a function const ref parameter). Am I right? Right. I have two observations myself: - To be more useful, function parameters should not insist on immutable data, yet we type string all over the place. - To be more useful, functions should not insist on the mutability of the data that they return. The following function makes a new string: char[] endWithDot(const(char)[] s) { return s ~ '.'; } char[] s; s ~= hello; auto a = endWithDot(s); It is good that the parameter is const(char) so that I could pass the mutable s to it. But the orthogonal problem of the type of the return is troubling. The result is clearly mutable yet it can't be returned as such: Error: cannot implicitly convert expression (s ~ '.') of type const(char)[] to char[] We've talked about this before. There is nothing in the language that makes me say the returned object is unique; you can cast it to mutable or immutable freely. I saw that std.string functions use assumeUnique from std.exception. As for your example, it probably should be: char[] endWithDot(const(char)[] s) { return s.dup ~ '.'; } 5. Align attribute. http://dlang.org/attribute.html#align struct S { align(4) byte a; // placed at offset 0 align(4) byte b; // placed at offset 1 } Explain this please. I don't know more than what the documentation says but I remember reading bugs about align(). 6. Array slices manipulation. a[] += 1; works but a[]++ doesn't. Not so important but just wondering: why, and is it intended? Again, I remember discussion and limitations about this feature. Fixed-length arrays have better support and the regular increment works: double[3] a = [ 10, 20, 30 ]; ++a[]; ++a[] works, but a[]++ doesn't. 7. Anonymous structs. In C you can write: struct { int a; } s = {10}; printf(%d\n, s.a); In D you must declare the struct first: struct S { int a; }; S s = {10}; writeln(s.a); Why doesn't D allow anonymous structs? It may be related to palsing. D does not require the semicolon at the end of the struct definition, so it wouldn't know what 's' is: struct { int a; } // definition (of unmentionable type :) ) s = {10}; // unknown s There could be special casing but I don't think that it would be worth it. Sounds reasonable. Ali
Re: Reading about D: few questions
Mr. Anonymous: With the given example of: byte[1024] buffer = void; So does the GC really scan this byte array? The current D GC is not precise, so I think the current DMD+GC scan this array. Future better compilers/runtimes probably will be able to avoid it (with a shadow stack the gives precise typing information at runtime, used by a precise GC). The solution works but is not as clean as just using array ~= c; Is there any way (language, runtime, or phobos) to declare an array that would reallocate memory by chunks, which are multiple of x? Appending to built-in D arrays is several times slower than doing the same thing to a C++ vector, but in many situations the performance is enough. When it's not enough there is the capacity function in the object module. Or for even better performance the appender in std.array, that gives performance just a little worse than the C++ vector push back. Is there any use for const when defining variables? As I see it, there is no use for using e.g. const int x;, as it can't be modified anyway; const int x = 5 + foo(y) * bax(z); It's better to use immutable or const everywhere this is possible and doesn't give you too many problems. In my D2 code about 70-90% of variables are now const or better immutable. This avoids some bugs and will help future compilers optimize code better. 5. Align attribute. http://dlang.org/attribute.html#align struct S { align(4) byte a; // placed at offset 0 align(4) byte b; // placed at offset 1 } Explain this please. I don't know. Keep in mind that DMD has many bugs, almost 50-100 gets removed every month. 6. Array slices manipulation. a[] += 1; works but a[]++ doesn't. Not so important but just wondering: why, and is it intended? It's a compiler bug. I think it's already in Bugzilla (but take a look in Bugzilla if you want to be sure). 7. Anonymous structs. In C you can write: struct { int a; } s = {10}; printf(%d\n, s.a); In D you must declare the struct first: struct S { int a; }; S s = {10}; writeln(s.a); Why doesn't D allow anonymous structs? D doesn't allow top-level anonymous structs. ++a[] works, but a[]++ doesn't. Already known compiler bug. Ali: There is nothing in the language that makes me say the returned object is unique; you can cast it to mutable or immutable freely. The return value of strongly pure functions is implicitly castable to immutable. And sometimes inout helps. Bye, bearophile
Re: Reading about D: few questions
5. Align attribute. http://dlang.org/attribute.html#align struct S { align(4) byte a; // placed at offset 0 align(4) byte b; // placed at offset 1 } Explain this please. align is a huge mess imo. It matches the corresponding C compiler behavior So what's the point of align in the first place, if the compiler does what it wants anyway, see above? The only thing that really works is align(1) struct S {...} for packed structs.
Uninitialized Arrays and GC
On 23.12.2011 21:51, bearophile wrote: Mr. Anonymous: http://dlang.org/memory.html#uninitializedarrays It's said here ^ that: The uninitialized data that is on the stack will get scanned by the garbage collector looking for any references to allocated memory. With the given example of: byte[1024] buffer = void; So does the GC really scan this byte array? Or (sounds more logical to me) does it scan only reference types? If the latter is true, I think the example should use some kind of a pointer array. Also, in this case, I can't see why Uninitialized data can be a source of bugs and trouble, even when used correctly.? If the former is true, then, well, I'll ask more questions. The current D GC is not precise, so I think the current DMD+GC scan this array. Future better compilers/runtimes probably will be able to avoid it (with a shadow stack the gives precise typing information at runtime, used by a precise GC). Well, if that's really so, then it's not 100% reliable. e.g. you generate an array of random numbers, and one of them appears to be an address of an allocated array. This array won't free even if not used anymore.
Re: Reading about D: few questions
On 23.12.2011 19:47, Ali Çehreli wrote: On 12/23/2011 07:25 AM, Mr. Anonymous wrote: 2. Setting Dynamic Array Length. http://dlang.org/arrays.html#resize A more practical approach would be to minimize the number of resizes The solution works but is not as clean as just using array ~= c; Is there any way (language, runtime, or phobos) to declare an array that would reallocate memory by chunks, which are multiple of x? Array expansion is already more efficient than they look at first. This article is a good read: http://www.dsource.org/projects/dcollections/wiki/ArrayArticle std.array.Appender is what I was talking about :)
Re: Reading about D: few questions
On 12/23/2011 11:51 AM, bearophile wrote: Ali: There is nothing in the language that makes me say the returned object is unique; you can cast it to mutable or immutable freely. The return value of strongly pure functions is implicitly castable to immutable. Is that working yet? The commented-out lines below don't compile with 2.057: void main() { char[] s = hello.dup; char[]am = endWithDot(s); const(char)[] ac = endWithDot(s); const(char[]) acc = endWithDot(s); // immutable(char)[] ai = endWithDot(s); // immutable(char[]) aii = endWithDot(s); } pure char[] endWithDot(const(char)[] s) { char[] result = s.dup; result ~= '.'; return result; } Also note that I could not use the better line below in endWithDot(): return s ~ '.'; as the type of the result is const(char)[]. I insist that it too should be castable to any mutable or immutable type. And sometimes inout helps. Yes but it is only when the types of the parameters and the result should be related. Bye, bearophile Ali
Re: Uninitialized Arrays and GC
On 12/23/2011 02:46 PM, Ali Çehreli wrote: On 12/23/2011 12:36 PM, Mr. Anonymous wrote: you generate an array of random numbers, and one of them appears to be an address of an allocated array. This array won't free even if not used anymore. OK, I misread what you said. I thought you were filling the array with random numbers. You are right. Ali
Re: Reading about D: few questions
On Friday, December 23, 2011 09:47:35 Ali Çehreli wrote: - To be more useful, function parameters should not insist on immutable data, yet we type string all over the place. That depends. If they're going to have to idup the data anyway, then it's better to require that the argument be immutable so that that cost is clear. The worst is taking const and then iduping, because then you're forced to idup strings which didn't need to be iduped. And in general, operating on strings is more efficient than mutable character arrays, because you can slice them with impunity, whereas you often have to dup or idup mutable arrays in order to avoid altering the original data. The area where the immutability becomes problematic is when you actually want to directly mutate a string - but that's generally a rather iffy thing to do with UTF-8 anyway, since you have to deal with the varying length of the various code points within the string. That being said, an increasing number of functions in Phobos are templated on string type so that you can use whatever string type that you want with them. And there is a push (at least with toString) to add the ability to put the result of a string function into an existing string of some variety (be it using a delegate or an output range). So, you'll be forced to use string less, but the reality of the matter is that in the general case you should probably be using string anyway (there are, of course, always exceptions). - To be more useful, functions should not insist on the mutability of the data that they return. The following function makes a new string: char[] endWithDot(const(char)[] s) { return s ~ '.'; } char[] s; s ~= hello; auto a = endWithDot(s); It is good that the parameter is const(char) so that I could pass the mutable s to it. But the orthogonal problem of the type of the return is troubling. The result is clearly mutable yet it can't be returned as such: Error: cannot implicitly convert expression (s ~ '.') of type const(char)[] to char[] We've talked about this before. There is nothing in the language that makes me say the returned object is unique; you can cast it to mutable or immutable freely. In general, D doesn't have features where the programmer says that something is okay. It's too interested in making guarantees for that. Either it can guarantee something, or you force it with a cast. I can't think of even one feature where you say that _you_ guarantee that something is okay. Casting is your only option. That being said, the language is improving in what it can guarantee and in what it can do thanks to those guarantees. For instance, if you have a pure function and the compiler can guarantee that the return value doesn't reference anything in the argumetns passed in, then the return value is implicitly convertible to whatever const-ness you want. If you want to be making such guarantees yourself, then what you typically have to do is templatize the function and take advantage of static if and D's compile-time reflection capabilities. Phobos does this quite a bit to improve performance and avoid having to duplicate data. Your particular example is quite easily fixed though. The issue is that the string which was passed in is typed as const(char)[], and the expression s ~ '.' naturally results in the same type. But it's quite clear that the resulting string could be of any constness, since it's a new string. So, just tell it what constness to have by casting it. - Jonathan M Davis
Re: Reading about D: few questions
On Friday, December 23, 2011 20:19:28 Mr. Anonymous wrote: I saw that std.string functions use assumeUnique from std.exception. As for your example, it probably should be: char[] endWithDot(const(char)[] s) { return s.dup ~ '.'; } No, that allocates _two_ strings - one from dup and one as the result of the concatenation. It should either be auto retval = s.dup; retval ~= '.'; return retval; or return cast(char[])(s ~ '.'); The problem is that because s is const(char)[], the result of the concatenation is that type. But it's guaranteed to be a new string, so the cast is fine. It's arguably better to use the first version though, since it doesn't require a cast. - Jonathan M Davis
Re: Reading about D: few questions
On Friday, December 23, 2011 14:51:06 bearophile wrote: And sometimes inout helps. Yeah, good point. I keep forgetting about inout, since it didn't work properly before. So, the best way to implement Ali's function would be inout(char)[] endWithDot(inout(char)[] s) { return s ~ '.'; } - Jonathan M Davis
Re: Reading about D: few questions
On Friday, December 23, 2011 14:51:21 Ali Çehreli wrote: On 12/23/2011 11:51 AM, bearophile wrote: Ali: There is nothing in the language that makes me say the returned object is unique; you can cast it to mutable or immutable freely. The return value of strongly pure functions is implicitly castable to immutable. Is that working yet? The commented-out lines below don't compile with 2.057: void main() { char[] s = hello.dup; char[]am = endWithDot(s); const(char)[] ac = endWithDot(s); const(char[]) acc = endWithDot(s); // immutable(char)[] ai = endWithDot(s); // immutable(char[]) aii = endWithDot(s); } pure char[] endWithDot(const(char)[] s) { char[] result = s.dup; result ~= '.'; return result; } Well, that's not strongly pure - only weakly pure - so if the optimization is only for strongly pure functions, then that won't work. I know that it _could_ be done with weakly pure functions as well (such as your example here), but I'm not exactly sure what it does right now. The feature is new, so it doesn't yet work in all of the cases that it should, and it's not entirely clear exactly far it will go. IIRC, Daniel Murphy and Steven were discussing it a while back, and it clearly didn't do as much as it could, and it wasn't entirely clear that it ever would beacuse of the increased complications involved. However, it wil almost certainly work in more cases in the future than it does now as the feature is improved. - Jonathan M Davis
Re: Reading about D: few questions
Jonathan M Davis: The feature is new, so it doesn't yet work in all of the cases that it should, and it's not entirely clear exactly far it will go. IIRC, Daniel Murphy and Steven were discussing it a while back, I have very recently opened another thread about it, but unfortunately it didn't attract a lot of attention: http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.Darticle_id=153041 and it wasn't entirely clear that it ever would beacuse of the increased complications involved. Yeah. Ali: return s ~ '.'; as the type of the result is const(char)[]. I insist that it too should be castable to any mutable or immutable type. Add a request in Bugzilla if it's not already present. I don't know how much complex it is to implement in the compiler. Bye, bearophile
Re: Reading about D: few questions
On 12/23/2011 03:16 PM, Jonathan M Davis wrote: On Friday, December 23, 2011 09:47:35 Ali Çehreli wrote: - To be more useful, function parameters should not insist on immutable data, yet we type string all over the place. That depends. If they're going to have to idup the data anyway, then it's better to require that the argument be immutable so that that cost is clear. The worst is taking const and then iduping, because then you're forced to idup strings which didn't need to be iduped. That would be leaking an implementation detail to the user. Besides, it doesn't solve the problem if the user is in the middle: void user(const(char)[] p) { writeln(endWithDot(p)); } The user itself would be forced to take immutable, but this time the reason is different: not because he is passing a copy optimization of its own, but because he is passing endWithDot()'s copy optimization to its caller. immutable would have to be leaked all the way up just because a low level function decided to make a copy! Perhaps the guideline should be: Everybody should take by immutable references so that this leaking of immutable through all layers should not be a problem in case a low-level function decided to make a copy. And in general, operating on strings is more efficient than mutable character arrays, because you can slice them with impunity, whereas you often have to dup or idup mutable arrays in order to avoid altering the original data. Agreed. But immutable on the parameter list is an insistence: The function insists that the data be immutable. Why? Because it is going to store it for later use? Perhaps share it between threads? It is understandable when there is such a legitimate reason. Then the caller would see the reason too: oh, takes immutable; that means my data may be used later as is. That being said, an increasing number of functions in Phobos are templated on string type so that you can use whatever string type that you want with them. And there is a push (at least with toString) to add the ability to put the result of a string function into an existing string of some variety (be it using a delegate or an output range). So, you'll be forced to use string less, Good. Ranges are more and more becoming thinking in D. Perhaps we should be talking about a range that appends a dot at the end of the existing elements. but the reality of the matter is that in the general case you should probably be using string anyway (there are, of course, always exceptions). I am looking for simple guidelines when designing functions. It is simple in C++: take data by reference to const if you are not going to modify it. (It is questionable whether small structs should be passed by value instead, but that's beside the point.) In C++, passing by reference to const works because the function accepts any type of mutability and a copy is avoided because it's a reference. In D, immutable is not more const than const (which was my initial assumption); it is an additional requirement: give me data that should never change. My point is that this requirement makes sense only in rare cases. Why would a function like endWithDot() insist on how mutable the user's data is? - To be more useful, functions should not insist on the mutability of the data that they return. The following function makes a new string: char[] endWithDot(const(char)[] s) { return s ~ '.'; } char[] s; s ~= hello; auto a = endWithDot(s); It is good that the parameter is const(char) so that I could pass the mutable s to it. But the orthogonal problem of the type of the return is troubling. The result is clearly mutable yet it can't be returned as such: Error: cannot implicitly convert expression (s ~ '.') of type const(char)[] to char[] We've talked about this before. There is nothing in the language that makes me say the returned object is unique; you can cast it to mutable or immutable freely. In general, D doesn't have features where the programmer says that something is okay. It's too interested in making guarantees for that. Either it can guarantee something, or you force it with a cast. I can't think of even one feature where you say that _you_ guarantee that something is okay. Casting is your only option. [...] I know. I used the wrong words. Yes, the compiler should see what I see: the returned object is unique and can be elevated to any mutability level. Your particular example is quite easily fixed though. The issue is that the string which was passed in is typed as const(char)[], and the expression s ~ '.' naturally results in the same type. But it's quite clear that the resulting string could be of any constness, since it's a new string. So, just tell it what constness to have by casting it. That's the other side of the problem: Why would the function dictate how the caller should treat this piece of data?
Re: Reading about D: few questions
The core problem for a number of these situations is how types are handled with regards to expressions. In an expression such as char[] arr = s ~ '.'; the type of the value being assigned is determined _before_ the assignment is done. So, even though in theory the compiler could make it work, it doesn't, because by the time it's looking at the type being assigned to, it's too late. There would need to be a fundamental change in how the language functions in order to fix issues like this. pure can do it when it can not because it's able to look at what the return type is and changing the result of the expression accordingly but because it has guarantees which make it so that it knows that the return value could be converted to any level of constness and still be valid. The types used in the expressions internally are generally irrelevant. So, while I completely agree that it would be an improvement if the compiler did a better job with implicit conversion when it could theoretically be done, I'm not sure how much of that we're actually going to end up seeing simply because of how the language and type system works in terms of the order of evaluation. - Jonathan M Davis