Re: setjmp / longjmp
On 27/04/2015 10:41, ketmar wrote: snip i believe this has something to do with exception frames. but it needs further investigation. What is an exception frame, exactly? Moreover, are these frames applicable even in sections of code where no throwing or catching of exceptions takes place? Stewart. -- My email address is valid but not my primary mailbox and not checked regularly. Please keep replies on the 'group where everybody may benefit.
Re: setjmp / longjmp
On 26/04/2015 06:56, ketmar wrote: snip you shouldn't use setjmp/longjmp in D. use exceptions instead. something like this: snip True in the general case. Still, there must be some reason that trying it in D causes an AV (even if I disable the GC). I remain curious about what that reason is. Some time ago, just for fun, I wrote an Unlambda to D compiler. Except that I couldn't get the c builtin to work properly. Exceptions cover typical uses cases, but a subtlety of it is that (roughly speaking) the continuation it emits can escape from the function it is passed into, and then when the continuation is later invoked it should return the program to the point at which c was invoked. Essentially, it can wind the stack as well as unwinding it. I envisaged that, maybe with the aid of setjmp and some trick to get GC to work with it, it could be made to work. Stewart. -- My email address is valid but not my primary mailbox and not checked regularly. Please keep replies on the 'group where everybody may benefit.
Re: multidimensional array
On 28/09/2014 08:48, ketmar via Digitalmars-d-learn wrote: On Sun, 28 Sep 2014 04:24:19 + Joel via Digitalmars-d-learn digitalmars-d-learn@puremagic.com wrote: struct Spot { bool dot; } spots = new Spot[][](800,600); btw, does anybody know why i can do `new ubyte[256];` but not `new ubyte[256][256];`? hate that. You can do `new ubyte[256][256]`, if the destination type is a ubyte[256][]. The reason is that you are performing an allocation of the form `new T[n]`, which means allocate an array of n instances of type T. In this case, T is ubyte[256], which is a static array type. Stewart. -- My email address is valid but not my primary mailbox and not checked regularly. Please keep replies on the 'group where everybody may benefit.
Re: Limit number of compiler error messages
On 22/05/2012 18:36, cal wrote: snip my build command 21 | head -n number of lines you want to see Where my build command is your dmd/rdmd/build script command. There's probably something similar you could use on Windows, I don't really know though. By something similar do you mean a way of piping stderr, or a head utility? A head utility is trivial to code. Of course, a way to pipe stderr is another matter. They are probably all valid errors, I am porting a rather large C file to D and it takes a few seconds (perhaps 10 seconds) for the compiler to finish listing all the things I haven't fixed up yet, makes the process a bit more tedious is all. No biggy, thought there might be a switch I missed. Interestingly, I don't seem able to redirect the compiler output on Windows, or even pipe it. What version of Windows are you using? Modern versions support 2 to redirect stderr to a file. But 2| doesn't seem to work correspondingly (at least under Vista, don't know about Win7) - by the looks of it it just passes 2 as an argument to the program and pipes stdout as usual. Maybe a utility could be made along similar lines to Rederr (which I published somewhere on these 'groups OUAT) Stewart.
Re: ProjectEuler problem 35
On 19/05/2012 16:13, maarten van damme wrote: A huge optimization could be made by storing and int array of already found primes and test all primes smaller then half the to-test number. this will speed up a lot. Do you mean build an array of already-found primes and use them to test new primes? You need only to try dividing by each prime up to the square root of the number being tested. Another huge improvement could be made with hardcoding everything up to the prime 3 and then iterate with intervals of 2 instead of 1. Yes, that's a common optimisation. Faster still would be to test 6k-1 and 6k+1 for each positive integer k. Indeed, I've done more than this in my time: hard-coded all the primes up to 30 and the residues modulo 30 that can possibly be of primes above 30. Stewart.
Re: ProjectEuler problem 35
On 16/05/2012 10:46, Dmitry Olshansky wrote: snip Don't ever do that. I mean allocating memory in tight cycle. Instead use circular buffer. (just use the same array and wrap indexes) snip You might as well not use a string representation at all. At the beginning of the loop, calculate the number of digits in n, then pow10 = 10 ^^ (digits - 1). Then cycle with n = n / 10 + (n % 10) * pow10; Stewart.
Re: Transforming a range back to the original type?
On 02/05/2012 22:01, Jacob Carlborg wrote: Is there a general function for transforming a range back to the original type? If not, would it be possible to create one? To sum it up, it can't be done in the general case. The range API doesn't know or care about the underlying data structure. That's half the point of it. The underlying data structure might not even exist. An example is a range used as a file stream, a random number generator or to lazily generate a mathematical sequence. Moreover, what would you want such a function to return if the range is: - a file stream with a cache - an array wrapper to loop infinitely through it? - a concatenation of ranges that may be of different types? Moreover, even if there were some range with an underlying container classification, it would be an extra burden on the writer of the range wrapper to implement this. If you want to generate a range that views a container in a certain way, and then construct a container of the original type (or indeed any type) from that range, then create the container and then use a foreach loop on the range (or a .save of it, if you want to keep the range afterwards) to put the data into the container. Stewart.
Re: Docs: Section on local variables
On 26/04/2012 08:26, Timon Gehr wrote: snip Another thing: It might not be unused in every static code path. One way to deal with this would be to do the checking before conditional compilation. That said, I've a feeling that mixin expansion might get in the way of this. Even more important: template isInputRange(R) { enum bool isInputRange = is(typeof( { R r; // can define a range object if (r.empty) {} // can test for empty r.popFront(); // can invoke popFront() auto h = r.front; // can declare an unused variable snip cast(void) r.front; Stewart.
Re: Docs: Section on local variables
On 26/04/2012 08:26, Timon Gehr wrote: snip template isInputRange(R) { enum bool isInputRange = is(typeof( { R r; // can define a range object if (r.empty) {} // can test for empty r.popFront(); // can invoke popFront() auto h = r.front; // can declare an unused variable }())); } snip This is indeed a blocker for fixing it to work according to the current spec. I've just filed http://d.puremagic.com/issues/show_bug.cgi?id=7989 to address it. Stewart.
Re: Docs: Section on local variables
On 26/04/2012 15:05, Stewart Gordon wrote: snip http://d.puremagic.com/issues/show_bug.cgi?id=7989 From JMD: The fact that isInputRange and isForwardRange rely on declaring variables which aren't used being legal. It would be really annoying for unused local variables to be illegal when dealing with template constraint stuff like isInputRange and isForwardRange. Code would have to be needlessly contorted to deal with that fact, and you wouldn't ever get a good error about why the result of the template was false, because it would be part of a template constraint. IHMO, the very issue that this bug report brings up highlights a good reason why unused local variables should continue to be ignored by the compiler. (on 3960) I think that issue# 7989 is a great argument for why there shouldn't be any warnings or errors for unused variables. Such would needlessly make writing template constraints harder. Since this is relevant to both issues, I'll continue the discussion here. I can begin to see why it makes errors for unused variables a bad idea. But why no warnings? Obviously the user wouldn't like to see warnings thrown at them when they try using templates with such constraints. But: - The average programmer is, the vast majority of the time, not writing template constraints, but trying to write bug-free application code. - A quality compiler would swallow warnings generated by the content of IsExpressions, just as it already swallows errors generated by them - the only difference being that warnings don't cause the IsExpression to return false. Stewart.
Re: Docs: Section on local variables
On 26/04/2012 22:52, bearophile wrote: snip For uncommon situations like isInputRange a specific annotation solves the problem cleanly. As does the compiler swallowing warnings in the content of an IsExpression as I already suggested. snip How many C/C++ programmers do you know that use lints? I think not enough. The Microsoft C++ compiler and Clang are adding more and more compile-time tests, replacing lints, this a trend D designers can't ignore. So saying leave it to lints it's almost like saying ignore the problem. I agree. http://dlang.org/overview.html under Who D is for: Programmers who routinely use lint or similar code analysis tools to eliminate bugs before the code is even compiled. My impression from this has been that D aims to eliminate (or at least minimise) the need to use lint-type tools, by making the code smells lint is made to catch illegal code and therefore caught by the compiler. Stewart.
Re: Docs: Section on local variables
On 21/04/2012 19:24, H. S. Teoh wrote: snip In finished code, it's obviously a bad thing to have unused variables (unless the compiler optimizes them away, Whether the compiler optimises it away or not, an unused variable is a code smell. Complaining about unused variables serves as a warning to the programmer that there's probably a bug in the program. Even if it's left over from debugging, it looks silly, and might lead other people reading the code to believe something's wrong. but that's not happening 'cos it depends on flow analysis, which would have let us spit out warnings about it in the first place.) How does seeing that there are no references to a variable anywhere in its scope depend on flow analysis? So do you prefer just an unused variable warning that comes out only when you use -wi/-w? A problem I've seen in D.learn is that lot of people here doesn't seem to use -wi/-w. So you think compiler warnings should be compulsory - with perhaps a CLO just to control whether they cause the compilation to fail? Or maybe, on the contrary, this unused variable error should be suppressed only if the D code is compiled with -debug? I don't know if conflating unused variable warnings with -debug is a good thing. Just like the conflation of -release with the opposite of -debug or -unittest. snip I don't really like this idea either. The point of -debug is to add code to the program for debugging. You might need to switch this debugging code on/off independently of whether you have unused variables. Two possibilities I can see: - Keep the statement in the spec, and fix DMD to implement it properly. Maybe add a CLO to suppress errors such as this one that are only there to catch bugs. - Remove the statement from the spec, and implement a warning in DMD. Stewart.
Re: Docs: Section on local variables
On 21/04/2012 17:26, Andrej Mitrovic wrote: snip Next thing you know the compiler will start warning me when I indent my code with uneven number of spaces! Or more usefully, warn if you have a mishmash of tab and space indentation. How do indent-sensitive languages (Haskell, Python, whatever else) deal with mixed tab/space indentation, for that matter? Stewart.
Re: Docs: Section on local variables
On 25/04/2012 17:10, Andrej Mitrovic wrote: On 4/25/12, Stewart Gordonsmjg_1...@yahoo.com wrote: Even if it's left over from debugging, it looks silly, and might lead other people reading the code to believe something's wrong. There's about a million ways to make code unreadable, and nobody writes pitch-perfect code that has absolutely no leftover code or comments. Exactly. But good-quality compilers help programmers in that direction in various ways. And what if you're refactoring and you do multiple builds every couple of seconds? You add a variable, remove it, etc etc. Enabling this warning will just make for a noisy compiler. But if the spec stays the same, the compiler needs to generate an _error_ for it in order to conform. If this statement is removed from the spec, then it will be a matter of adding a warning. But this is part of why warnings are optional in DMD. By enabling warnings in the compiler in the first place, the programmer is asking to be informed of things like this. Keeping variables clean is the responsibility of the programmer and not the compiler. If it doesn't affect the semantics of code the compiler should shut up. Please don't turn the compiler into a reincarnation of Clippy. So you think that import std.stdio; void main() { int a, b; a + b; return; writefln(Hello, world!); } should generate no errors or warnings whatsoever? Stewart.
Re: Docs: Section on local variables
On 25/04/2012 21:12, Andrej Mitrovic wrote: snip I'm really only talking about: void a() { int x; } What is the distinction you're making exactly? And of course: void a() { bool state; ... if (state) { } } You mean an empty if body should trigger something? Or shouldn't? OK, so I can see a similarity in that it's likely to occur when disabling portions of code for debugging purposes. Not just debugging the program in which it is present, but also creating testcases for compiler/library bug reports. I'd like the warnings to be individually selectable, just like in GCC. Btw, here's a trick question, should the compiler warn about this case? void main() { new Foo(); // or even Foo foo = new Foo; } An interesting one. Sometimes a constructor may hook the object up to something. I've probably done this myself on a number of occasions. Though I can't think of examples OTTOMH. But an example in C++ comes from my last job. The application framework developed in-house includes a class template used to trigger events on construction and destruction. To use it, one would just construct an object of that type. In many cases, it would just be a declaration of a variable of that type (since C++ classes are value types) - the variable will never be used again, but the object's construction triggers stuff. Stewart.
OT: Indent-sensitive languages again (was: Docs: Section on local variables)
On 25/04/2012 12:30, Stewart Gordon wrote: On 21/04/2012 17:26, Andrej Mitrovic wrote: snip Next thing you know the compiler will start warning me when I indent my code with uneven number of spaces! Or more usefully, warn if you have a mishmash of tab and space indentation. How do indent-sensitive languages (Haskell, Python, whatever else) deal with mixed tab/space indentation, for that matter? Just found out http://urchin.earth.li/~ian/style/haskell.html http://www.secnetix.de/olli/Python/block_indentation.hawk that both Haskell and Python uses a tab size of 8 characters. Personally, I think they should error if the meaning of a section of code depends on the tab size. OTOH, YAML avoids the issue in the strictest way possible: forbidding tab characters. I wonder if there are other languages that require you to indent with tabs. But one possible design for languages like these is to allow indentation to be either entirely spaces or entirely tabs, but not a mixture. This would also be a good way for linters for a variety of languages to behave. Another way would be to allow tabs, spaces or a mixture, with the only restriction being that a given block must be consistently indented with the same sequence of tabs/spaces. Stewart.
Re: Formatting dates in std.datetime?
On 20/04/2012 21:29, H. S. Teoh wrote: Is there a way to format std.datetime.Date objects with a custom format string? My utility library has a datetime module with a custom formatting facility. http://pr.stewartsplace.org.uk/d/sutil/ The format string scheme is one of my own design, using repeated-letter format specifiers similar to those found in some other schemes, and designed to be logical, natural-looking, extensible and easy to remember. It doesn't currently have functions to convert between its types and those in std.datetime, but it's straightforward to construct a DateTimeComponents from a std.datetime.Date structure and then call its format method, if you still want to use the std.datetime API and just use my library for formatting. In particular, I'd like to reuse month short names defined in std.datetime, but it appears that the names are private. I'd really rather not duplicate them by hand, if there's a way to get them. snip My library has these arrays public. But I agree that it was somewhat gratuitous to make them private in std.datetime. Stewart.
Re: Docs: Section on local variables
On 20/04/2012 01:53, Andrej Mitrovic wrote: Can I remove this section from the D docs, in functions? : Local Variables It is an error to use a local variable without first assigning it a value. The implementation may not always be able to detect these cases. Other language compilers sometimes issue a warning for this, but since it is always a bug, it should be an error. This does seem to be a total contradiction of the principle that's stated elsewhere in the D spec that variables are always initialised. It is an error to declare a local variable that is never referred to. Dead variables, like anachronistic dead code, are just a source of confusion for maintenance programmers. snip Why do you want to be able to declare local variables and then never use them? Stewart.
Re: Clearly Label D1/D2/Tango/Phobos
On 18/04/2012 13:34, Paul wrote: I bought the book and am trying to patiently learn this language. I follow various tutorials here and around the web that frequently won't compile. I suspect it has something to do with D1/D2/Phobos/Tango and not just really poor unvetted tutorials. It would really be helpful if those providing references, code snippets, tutorials, etc clearly identify the context (i.e D1/D2/Phobos/Tango). I just think it would help accelerate the spread and acceptance of this language if more of the code worked as listed. snip Even the particular version of (DM)D in which it has been tested, given how much the language has been changing. There have been language-level changes to D2 very recently, and bug 1824 is one of probably many that still need to be dealt with before it can stabilise. Stewart.
Re: T : T*
On 13/04/2012 19:47, Jonathan M Davis wrote: I'd just like to verify that my understanding of T : T* in this template is correct: struct S(T : T*) snip it appears that the compiler is instead taking this to mean that the pointer part of the type should be stripped from the template argument's type. snip Yes. It's more or less syntactic saccharin for struct S(U : T*, T) { T t; } Stewart.
Re: Multiple %s format specifiers with a single argument
On 09/04/2012 18:35, Andrej Mitrovic wrote: On 4/9/12, Jonathan M Davisjmdavisp...@gmx.com wrote: Posix positional arguments seem to work for writefln but not format for whatever reason. Report it as a bug. Thanks, http://d.puremagic.com/issues/show_bug.cgi?id=7877 Andrej, are emails from Bugzilla not getting through to you? And Jonathan, you ought to know that you already submitted one of the duplicate bug reports about this. You shouldn't submit bug reports without searching first anyway. Always include resolved bugs in the search - the bug you're about to report might have been fixed ready for the next release, and duplicates already in the system help to catch different ways of phrasing the same statement, among other things. Stewart.
Re: Multiple %s format specifiers with a single argument
On 10/04/2012 13:30, Andrej Mitrovic wrote: On 4/10/12, Stewart Gordonsmjg_1...@yahoo.com wrote: Andrej, are emails from Bugzilla not getting through to you? I'm not getting any emails. Bugzilla stopped emailing me for quite a while now, I don't know why (except the monthly password reminder). snip Assuming that you did hit the Submit Changes button and that the email address you have registered with Bugzilla is correct, I don't know. Have you checked with your email provider to see if they're being flagged as spam? On 4/10/12, Stewart Gordonsmjg_1...@yahoo.com wrote: You shouldn't submit bug reports without searching first anyway. I did, but the default search box doesn't seem to search duplicate reports (I didn't know this until now). E.g. if I search for format positional I get this lone result: http://d.puremagic.com/issues/buglist.cgi?quicksearch=format+positional Indeed, it seems that quick search is designed only as a means of quickly finding an open bug that you know is in the system. snip There's an option in advanced search and remember these as my default search options, but even though I have this ticked and it says it saved it, it doesn't actually work. It seems that and remember these as my default search options affects only the advanced search. Or are you finding that it isn't working even there? Stewart.
Re: SUL for Posix
On 05/04/2012 14:51, Jacob Carlborg wrote: snip http://dlang.org/phobos/std_getopt.html But it might not do what you want. Where is the code in std.getopt that has any relevance whatsoever to what smjg.libs.util.datetime or smjg.libs.util.commandline is for? Stewart.
Re: SUL for Posix
On 07/04/2012 17:54, Jacob Carlborg wrote: snip Both std.getopt and mjg.libs.util.commandline handle command line arguments? What's that to do with anything? If the code I need to finish smjg.libs.util.commandline is somewhere in std.getopt, please tell me where exactly it is. If it isn't, then why did you refer me to it? That's like telling someone who's writing a bigint library and struggling to implement multiplication to just look in std.math. After all, they both handle numbers. Stewart.
Re: SUL for Posix
On 07/04/2012 20:16, Jacob Carlborg wrote: snip I don't know what your module is supposed to do. Then how about reading its documentation? http://pr.stewartsplace.org.uk/d/sutil/doc/commandline.html If there's something you don't understand about it, this is the issue that needs to be addressed, rather than wildly guessing that some Phobos module provides the answer. Stewart.
Re: Read a unicode character from the terminal
On 31/03/2012 23:14, Stewart Gordon wrote: snip You might want to try the console module in my utility library: http://pr.stewartsplace.org.uk/d/sutil/ (For D1 at the moment, but a D2 version will be available any day now!) The D2 version is now up on the site. Jacob - would you be up for helping me with testing/implementation of my library on Mac OS? If you do a search for todo you'll see what needs to be done. Some of it will benefit Unix-type systems generally. If perchance you have a big-endian CPU, testing the bit arrays on it would also be of value. Stewart.
Re: Read a unicode character from the terminal
On 04/04/2012 17:37, Jacob Carlborg wrote: snip Sure I can help you with testing. I have a lot on my own table so I don't have any time for implementing things (maybe some small things). If I may ask, what is the point of this library? Just to hold some miscellaneous utility classes/structs/functions. Doesn't it duplicate functionally that's already available in Phobos and/or Tango? snip It certainly does in places. But what matters is that it contains functionality that isn't present in Phobos (or wasn't present in Phobos at the time I wrote it). Stewart.
Re: Read a unicode character from the terminal
On 31/03/2012 16:56, Jacob Carlborg wrote: How would I read a unicode character from the terminal? I've tried using std.cstream.din.getc but it seems to only work for ascii characters. If I try to read and print something that isn't ascii, it just prints a question mark. What OS are you using? And what codepage is the console set to? You might want to try the console module in my utility library: http://pr.stewartsplace.org.uk/d/sutil/ (For D1 at the moment, but a D2 version will be available any day now!) Stewart.
Making sense of ranges
The documentation for std.range states http://dlang.org/phobos/std_range.html This module defines the notion of range (by the membership tests isInputRange, isForwardRange, isBidirectionalRange, isRandomAccessRange), range capability tests (such as hasLength or hasSlicing), and a few useful range incarnations. But that intro doesn't describe what a range actually is. Here's what I've made out so far: - Ranges are basically a generalised API for accessing a container or stream that is linear in logical structure and can have any element type. - What is a range and what isn't is determined by compile-time duck typing - testing whether it implements certain methods. - A range over a finite data structure is essentially equivalent to a start/end iterator pair as used by various C++ STL functions. - Where a function in std.range is described as iterating through ranges in a particular way, what this function does is to return a range that delivers the resulting sequence. Have I got all this right? Things I'm confused by: - One of the expansions of put is r.front = e; r.popFront(); What has putting something at the front of a range and then popping it to do with outputting to the range? - Why is a range that can save checkpoints called a forward range? Stewart.
Re: Making sense of ranges
On 24/03/2012 18:57, Ali Çehreli wrote: snip Iterating an output range is also by popFront(). So what it says is, put this element to the output range and advance the range. There is a gotcha about this when the output range is a slice: Whatever is just put into the range is popped right away! :) [2] I'm beginning to get it now: the purpose of an output range is to put new data into the underlying container. So once you've put something in, the remaining range is what's left to be populated. I had been thinking of outputting in terms of appending to the range, hence the confusion. - Why is a range that can save checkpoints called a forward range? I agree. Here is my guess: The name of the ForwardRange comes from the fact that it is not double-ended. It can go only in one direction. snip Bidirectional ranges are forward ranges as well. But I've just had a look at STL iterators, and it seems that the range category hierarchy has been lifted from that. There, a forward iterator combines the functionality of an input iterator and an output iterator, hence it's your basic iterator that can move forwards and do what it likes with the data it walks over. (It would seem that it's only an output iterator in that * returns an lvalue, which may or may not be actually assignable depending on the constancy of the element type.) In D ranges, OTOH, the only thing that distinguishes a forward range from a general input range is the presence of a save method to make a copy of it. Doesn't seem to have anything to do with either the forward name or the C++ origin thereof Something else I'm finding puzzling is moveFront, moveAt and moveBack. Is D trying to be C++11 or something? Move semantics don't seem to me to be useful in a language with GC. Stewart.
Re: Tail call optimization?
On 18/03/2012 21:28, bearophile wrote: Alex Rønne Petersen Wrote: Does D to tail call optimization of any kind? The D standard doesn't require the D compiler to perform that optimization (unlike Scheme). Currently both DMD and LDC are able to perform tail call optimization in some normal cases. And I presume GDC is able to do the same. What are normal cases? - where the function directly tail-calls itself? - where two functions mutually tail-call each other? - where a function tail-calls another non-recursively? And in the last case, I can see that it depends on being able to replace the caller's stack frame with the callee's. But what does this depend on - just the relative sizes of the functions' stack frames, or is it more subtle than that? Stewart.
Re: Simple operator precidence chart (and associativity)?
On 13/03/2012 23:14, Timon Gehr wrote: snip (Also, for associativity: Assign and OpAssign are right-associative and everything else is left-associative, correct?) Power is right-associative too. You forgot the conditional operator. And the relational operators are non-associative (a == b == c or similar is illegal). Stewart.
Re: delegate as memeber
On 21/02/2012 17:46, Jacob Carlborg wrote: On 2012-02-21 16:55, deadalnix wrote: snip You can implement a static opCall and use that instead of the constructor. But you don't have to call a static opCall. You can just declare a struct instance without any initialisation. Presumably half the point is to ensure that exceptionBuilder is still initialised in such cases. Stewart.
Re: Hex floats
On 16/02/2012 12:04, Don Clugston wrote: On 15/02/12 22:24, H. S. Teoh wrote: What's the original rationale for requiring that hex float literals must always have an exponent? For example, 0xFFi obviously must be float, not integer, so why does the compiler (and the spec) require an exponent? The syntax comes from C99. Do you mean the syntax has just been copied straight from C99 without any thought about making it more lenient? Stewart.
Re: More octal questions
On 15/02/2012 16:41, Jonathan M Davis wrote: snip They're not left over at all, and they have nothing to do with octal. snip They are something to do with octal: because in D an integer literal beginning with 0 is defined to be octal, the compiler must interpret them as such if it is going to accept them at all. Of course, under current D2 without -d, the compiler rejects zero-led integer literals greater than 07. But it's because of this octal legacy that it accepts up to 07 but not 08, 09 or 010. Still, what's the long-term plan? To remove octal literals completely, and allow decimal literals to have leading 0s? Or to continue to allow just up to 07 until the end of time? Stewart.
Re: Hex floats
On 15/02/2012 21:33, H. S. Teoh wrote: On Wed, Feb 15, 2012 at 01:24:13PM -0800, H. S. Teoh wrote: [...] This is ambiguous, since you could interpret 0xFFp0F as either 0xFFp0 followed by the suffix 'F', or 0xFFp0F with an exponent of 0x0F no suffix. [...] Actually, nevermind that. I misread the specs; the exponent is always in decimal, not hex, so this case is actually unambiguous. Maybe that's the reason for requiring the exponent - to render the F unambiguous. Though it could be done by defining the grammar such that the exponent is optional but the F suffix is allowed only after an exponent. But I wonder whether, if it's done that way, many people will inadvertently try to use F as a suffix to an exponentless HexFloat. So requiring an exponent might be to protect against this mistake. Up until another person makes the mistake of assuming the exponent of a HexFloat is meant to be hexadecimal Stewart.
Re: float.nan is not itself ?
On 14/02/2012 15:39, Joshua Reusch wrote: Hello, why does this assertion fail: assert(float.nan == float.nan); there is the std.math.isNaN function which works correctly, but why can I not just use the comparison ? A NaN typically denotes some kind of invalid computation. If the results of two invalid computations were considered equal, it would probably cause problems. Another way to think of it is to consider NaN as an unknown value. Two unknown values cannot be considered to be equal to each other. OK, so whether they're equal or not is actually unknown. If there were such a thing as bool.nan, equality comparisons in which at least one operand is NaN would probably evaluate to it. Indeed, null in SQL works this way. But in the absence of this in D, the best design has turned out to be to consider NaNs unequal. Stewart.
Re: maketrans and translate
On 13/02/2012 03:04, bearophile wrote: In the online docs I've seen that std.string.maketrans() is (going to be) deprecated. How do you adapt this code to the new regime? snip Use an associative array for the translation table. Or write your own functions that work in the same way as maketrans/translate. Stewart.
Re: inout constructor?
On 26/01/2012 15:27, Steven Schveighoffer wrote: snip auto tsm = TestStruct(xm); auto tsc = TestStruct(xc); auto tsi = TestStruct(xi); writeln(typeof(tsm).stringof); // TestStruct writeln(typeof(tsc).stringof); // const(TestStruct) writeln(typeof(tsi).stringof); // immutable(TestStruct) To actually get an immutable object (trying it on DMD 2.057), you need to use auto tsi = immutable(TestStruct)(xi); I think the reason is: Think of a constructor as a method that always returns this. The implicit this pointer points to a space that has been allocated in advance to hold the constructed object. this(inout(int)* d) inout { this.data = d; } auto ts = TestStruct(xi); is essentially inout(TestStruct) ctor(inout(int)* d) inout { this.data = d; return this; } TestStruct temp; auto ts = temp.ctor(xi); The implicit this pointer is a TestStruct* (mutable), but xi is an immutable(int*). The only way to match both is to match the inout as const, so a const is what it returns. But it doesn't work properly with a class instead of a struct at the moment. I'll note that I don't think this is currently supported, but I could see how it would be useful. You away from your usual testing station? However, in that bug report, there are no inout parameters besides the 'this' pointer, so I'm not sure what the purpose would be there. The purpose of it in the example is to be a minimal testcase for the bug. But in the general case, the purpose is to enable a mutable, const or immutable object to be constructed to wrap existing data that has the same constancy. Stewart.
Re: Error: 'this' is only defined in non-static member functions, not parse
For future reference and to elaborate on what others have said, if you're asking for help solving a problem with your code, then please: 1. Post a small, self-contained testcase that demonstrates the problem straight out of the box. Tips here: http://www.sscce.org/ 2. Post full compiler output (or runtime output, if it's a runtime problem) from the testcase. 3. State what compiler version and operating system you are using, as it may be relevant. Stewart.
Re: Taking a function or delegate as argument.
On 10/01/2012 19:56, Jacob Carlborg wrote: snip A template parameter with a template constraint will accept any callable type. Function pointer, delegate, struct/class overloading the call operator and so on. Indeed, this is done in the C++ STL quite a lot. The drawback is that templated methods lose their virtuality, because it cannot be known in advance on what types the template will be instantiated in order to populate the vtable. FWIW my utility library includes a delegate wrapper: http://pr.stewartsplace.org.uk/d/sutil/ (dgwrap works in both D1 and D2, though other bits of the library need updating to current D2) Stewart.
Re: Taking a function or delegate as argument.
On 10/01/2012 19:56, Jacob Carlborg wrote: snip A template parameter with a template constraint will accept any callable type. Function pointer, delegate, struct/class overloading the call operator and so on. Moreover, if you want to save the callback for later use, you need to distinguish the cases. But it really just boils down to: - if it's a global or static function, wrap it in a delegate - if it's a type with static opCall, wrap class.opCall in a delegate - if it's an object with an opCall, just use obj.opCall I've just had a look at std.functional.toDelegate and it seems it does this straight off. But the way it wraps a static function in a delegate is a lot more complicated than what my library does - is this just in order to support non-D linkage? And I see it has the same limitation of not supporting variadics. Stewart.
Re: An issue with lazy delegates
On 05/01/2012 05:26, Andrej Mitrovic wrote: snip The first call doesn't do anything because the delegate is wrapped inside of another delegate. I want this template to be versatile enough to be used by both lazy expressions and delegate literals, but I don't know how. snip If you have a delegate you want to use as a lazy expression, you can make the lazy argument a call to it onFailThrow!Exception({ to!int(x); }()); Of course, Peter's solution enables you to omit the () and just pass the delegate in, but it does mean that you can't lazily evaluate an expression to a delegate, unless you wrap it in a delegate literal. Stewart.
Re: Bug or feature? std.c.stdlib.exit() breaks RAII
On 29/12/2011 19:09, Jacob Carlborg wrote: snip excessive quote Could druntime hook up on the atexit function to run destructors and similar when the program exits? I'm not sure. Maybe it could be called upon to run static destructors and destruct heap-allocated objects. But in order to call scope guards and RAII, it would need to unwind the call stack, which could get complicated if you're trying to do it from within a function. It's much simpler not to use exit() and throw a custom exception instead. Stewart.
Re: typedef deprecated - now what ?
On 31/12/2011 13:34, Trass3r wrote: Basically it was deprecated because it's poorly defined and implemented. snip Would you care to elaborate? Moreover, if that's the only reason then why not improve it rather than getting rid of it? There are several types of typedefs that need to be available: parallel, opaque, supertype and subtype. See http://d.puremagic.com/issues/show_bug.cgi?id=5467 I see. So the built-in typedef is closest in semantics to subtype, but leaves bits to be desired. Stewart.
Re: typedef deprecated - now what ?
On 30/12/2011 10:35, Stephan wrote: is there a template or something in phobos to get the same typesafe behaviour of good old typedef ? Could someone please provide a link to the thread with the reasons for deprecating typedef? There are too many threads with the words typedef and deprecate in them for me to find it easily. Stewart.
Re: Void initialization
On 19/12/2011 18:11, Steven Schveighoffer wrote: On Mon, 19 Dec 2011 12:24:18 -0500, Bear joanylepri...@yahoo.fr wrote: gc.malloc actually returns void[] http://www.d-programming-language.org/phobos/core_memory.html#malloc Looks like void* to me... Or is there another function I'm not aware of? I think it should be GC.malloc, not gc.malloc, so maybe I'm missing something... snip You are. That the OP was talking about std.gc.malloc in D1, not the core.memory stuff in D2. Stewart.
Re: Void initialization
On 19/12/2011 12:12, bearophile wrote: Bear: snip float[] f = cast(float[])std.gc.malloc(x*4); Try something like this (untested): alias float TF; TF[] f = (cast(TF*)std.gc.malloc(x * TF.sizeof))[0 .. x]; snip I fail to see any real difference from the OP's code: - Why the alias? - std.gc.malloc returns the array with correct length according to my quick test, so the use of [0..x] is redundant - using TF.sizeof instead of 4 might fix things if on the user's platform float isn't 4 bytes long. Otherwise, while using .sizeof instead of a hard-coded number is better practice, it isn't going to get rid of an AV. But knowing what platform the OP is using and having a complete testcase for the AVs/ABEs might help to understand what is going on. Stewart.
Re: Void initialization
On 20/12/2011 18:12, bearophile wrote: snip Because in that code I have used three times a type (TF), auto allows to remove only one of them. The alias is not the best solution (a better solution is to put that code into a templated function), but repeating the same generic type more than one time is usually a source of bugs. I don't quite understand - why not just use float as it is? OK, so abbreviating it to TF saves 9 characters on that line, but the alias declaration and its trailing line break take up 16 characters, so you're not saving space at all. Moreover, the style guide discourages meaningless type aliases. (OK, so there are things I disagree with there, like using spaces not tabs for indentation, but that's another matter.) - std.gc.malloc returns the array with correct length according to my quick test, so the use of [0..x] is redundant Really? Well, as I have said I have not tested that code. Generally GC functions return a void*, so to create an array I think you need to slice it... If that were the case, the OP's code wouldn't have compiled. I made out that the OP was getting these errors at runtime, not compiletime. What is the code of your quick test? snip import std.stdio, std.gc; void main() { size_t x = 42; float[] f = cast(float[]) std.gc.malloc(x*4); writefln(f.length); alias float TF; f = (cast(TF*)std.gc.malloc(x * TF.sizeof))[0 .. x]; writefln(f.length); } Stewart.
Re: newbie question: Can D do this?
On 20/12/2011 20:36, Philippe Sigaud wrote: snip That is, it expects some values, then string/values couples as associative arrays. snip I've a recollection of seeing something like this in the PHP library, but I forget where. I believe it's used in some functions that have a lot of options to set, such that you'll typically just want to set a few of them in a given call. Stewart.
Re: Void initialization
On 20/12/2011 22:19, bearophile wrote: snip That's also why I have said a better solution is to wrap that code into a function template, so there is no need for an alias. snip So what you actually meant was to make TF a template parameter? That would make more sense. I can understand an alias being an intermediate step towards refactoring complex code into a template, but if you present it as part of a solution in simple cases like this then it's bound to get people wondering why on earth you're doing it, and possibly detract from what you're doing to actually (attempt to) solve the problem with the original code. Stewart.
Re: writef %d of string
On 02/12/2011 03:19, bearophile wrote: Stewart Gordon: It's perfectly legal code, If that code is legal, then in my opinion it's the rules of the language that are wrong and in need to be changed :-) You mean all programming languages should support CTFE for argument validation? What if the format string isn't even known at compile time in the first place? Some C(++) compilers understand printf and will warn if the format string doesn't match the arguments, but even this is rare AIUI. I don't know what 'AIUI' means. As I understand it. http://www.acronymfinder.com/ is your friend. And GCC (and Clang too) do it, so it's not a rare thing. I meant rare among the world's various C compilers. Are you going by usage statistics? To enforce well-formed format strings at compile time would require it to be made a language builtin. Or just a built-in rule, as in GCC. What do you mean by a built-in rule exactly? Or maybe template metaprogramming can do it. Of course. It's not hard to create something like this: writelnt!%d %f(53, 1.55); But I think you need a D compiler able to remove unneeded template instantiations from the binary, to avoid bloat. snip Maybe there's a way that the template instances can be very small, delegating most of the work to non-templated functions. Stewart.
Re: Formatted date
On 03/11/2011 23:58, Lishaak Bystroushaak wrote: Hello. Is there any way how to format date with formating strings? snip Yes. See the datetime stuff in http://pr.stewartsplace.org.uk/d/sutil/ Stewart.
Re: Formatted date
On 04/11/2011 00:51, Jonathan M Davis wrote: On Thursday, November 03, 2011 16:58 Lishaak Bystroushaak wrote: Hello. Is there any way how to format date with formating strings? Something like strftime in python; http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior Not currently. snip I could've sworn it was you I was talking to about the stuff in my library before. Are you an imposter? Stewart.
Re: writef %d of string
On 12/10/2011 23:41, bearophile wrote: This code, that a sane language/language implementation refuses at compile-time, runs: It's perfectly legal code, so the best a compiler can correctly do is give a warning. Some C(++) compilers understand printf and will warn if the format string doesn't match the arguments, but even this is rare AIUI. To enforce well-formed format strings at compile time would require it to be made a language builtin. Or maybe template metaprogramming can do it. import std.stdio; void main() { writefln(%d, hello); } And it outputs: ['h', 'e', 'l', 'l', 'o'] Is this good/expected/acceptable/buggy? It certainly should either throw an exception or generate more sane output such as Andrej is getting. What DMD version are you using? Stewart.
Re: Formatted date
On 01/12/2011 22:57, Jonathan M Davis wrote: snip There's a halfway decent chance that I posted in this thread prior to reading anything about your library or before I looked at it at all. And both Lishaak's and your computers had their clocks set several days fast at the time? Stewart.
Re: Make a variable single-assignment?
On 21/11/2011 20:06, Jesse Phillips wrote: What you are describing is Head Const, and is not available. http://www.d-programming-language.org/const-faq.html#head-const It will not be added as it doesn't provide any guarantees about the code that is useful to the compiler. It can't be added to the existing system without complicating the type system even more, which outweighs the benefits. snip Guarantees about the code don't need to be useful to the compiler - they can be just useful to the programmer. After all, this is the main point of DbC. And it doesn't need to be a full-fledged head const. At the simplest, a single-assignment variable could just be an rvalue - something of which the address cannot be taken and so the absence of head const becomes irrelevant. That said, it isn't much complexity to allow the address to be taken of such a thing final T data; auto ptr = data; with the following rules: - if T is a value type, immutable(something)[] or immutable(something)*, then data is an immutable(T)* - otherwise, data is a const(T)*. Once upon a time there was const/final/invariant. What exactly did final do back then? Stewart.
Re: Assert allowed to have side effects?
On 29/05/2011 14:03, bearophile wrote: Stewart Gordon: There are places where the spec fails to make a clear distinction between illegal code and incorrect code that the compiler may reject if it's smart enough. In D there are pure functions, so I think it's not too much hard for it to tell apart when the contents of an assert() are pure or not. My opinion is that the D compiler has to enforce purity inside assert(), to avoid bugs. Only if purity rules are relaxed. AIUI, one of the restrictions at the moment is that in a pure function only immutable data can be accessed. As long as this restriction remains in place, adding the restriction of purity to asserts would erode their usefulness. Stewart.
Re: Assert allowed to have side effects?
On 29/05/2011 09:44, simendsjo wrote: The documentation for assert, http://www.digitalmars.com/d/2.0/expression.html#AssertExpression, states that it's an error if the assert expression contains side effects, but it doesn't seem the compiler is enforcing this. There are places where the spec fails to make a clear distinction between illegal code and incorrect code that the compiler may reject if it's smart enough. The point of asserts is to check that the code is working correctly. By the time you come to release your software, you know that it's working correctly, and so the compiler ignores asserts in release mode. So the onus is on you to make sure the asserts don't have side effects. module assert_sideeffect; bool b; bool f() { b = !b; return b; } void main() { assert(f()); // oops.. changes b in debug mode snip It doesn't depend on debug mode. It depends on release mode. They're two independent compiler switches. Stewart.
Re: What is this strange alias syntax?
On 22/05/2011 21:51, Timon Gehr wrote: snip I suspect what Andrej actually meant is to kill treating function signatures as types in this way. And possibly enhancement request rather than bug. It is the opposite of an enhancement request. It means removing a feature that cannot be meaningfully substituted by other features. Unless you know a use case I've never heard of, it's no more a feature that cannot be meaningfully substituted by other features than the C preprocessor. (also, removing it increases the inconsistency of the language and makes the compiler more complex). I disagree. My point is that function types and data types have practically nothing in common. So your argument seems to me like claiming that D is inconsistent because classes and functions aren't interchangeable. snip True, if you use type in a broad sense. But it doesn't declare a variable of that type, and you can't use it as a type as such. Really, function signatures and data types are distinct entities and ought not to be interchangeable. You can alias any symbol. Data types and other symbols are distinct entities too. By your arguments, this is a bad thing to have. But do function signatures count as symbols? I'm not sure. Also, a function signature, while not a data type is still a _type_ (the broad sense is the D sense. You can do typeof(some_function)). And do what _with_ it, let alone that cannot be done by any other means? snip alias int func(); int main(){ static assert(is(typeof(main)==func); alias int function() func; static assert (is(typeof(main) == func)); return 0; } I do not get why anybody would want to remove the possibility to refer to function signatures. It can be handy for template constraining. snip Can you give an example? Stewart.
Re: What is this strange alias syntax?
On 22/05/2011 11:57, Steven Schveighoffer wrote: On Sat, 21 May 2011 05:15:32 -0400, Simen Kjaeraas simen.kja...@gmail.com wrote: snip It's the old C syntax for defining function pointers. Well, without the pointer. And that last part is important, because the latter example is an array of function pointers, with which D has no issue. Yes, and I thought we were killing that syntax because of how horrible it is? Indeed, that D has this notion of immediate function types is absurd: - it's mostly undocumented; indeed, no mention of it on type.html - there's no native D syntax for it, only the kludgy syntax inherited from C - it seems silly to have a type that you can't declare variables of and that (unlike void) has no obvious practical reason for its existence - it leads to such corner cases as http://d.puremagic.com/issues/show_bug.cgi?id=3650 Stewart.
Re: .init of field == type's initializer or field initializer?
On 20/05/2011 04:19, Andrej Mitrovic wrote: snip Foo.b.init is actually 0. Are the docs wrong, or is the compiler wrong? Let me know so I can fix the docs if necessary as I'm doing that now. Known issue: http://d.puremagic.com/issues/show_bug.cgi?id=5715 Stewart.
Re: toHash() and Interfaces
On 06/05/2011 13:02, Steven Schveighoffer wrote: snip D has this horrible notion that any interface can be for a COM object, even though COM interfaces can only inherit from IUnknown (known statically). Therefore, interfaces that don't inherit from IUnknown are not considered Objects, even though they could and should be. Firstly, IUnknown is defined in the Phobos files, not a language built-in. There might be multiple IUnknowns, defined in different modules (e.g. because some set of bindings has its own copy). How should the compiler identify the IUnknown to use? By name? By the signatures of functions specified within it? By fully qualified name? Secondly, I guess it's perfectly possible for some other system, besides COM, to create non-D objects that implement D interfaces. So you have to manually cast an interface to Object in order to call an Object function. Which you can do, if you are certain that the object will always be a D object. I guess the whole point is to protect you from those cases where you can't be sure. Stewart.
Re: Shouldn't duplicate functions be caught by DMD?
On 08/05/2011 09:41, bearophile wrote: Andrej Mitrovic: I think the compiler should check catch these mistakes at compile-time. I suggest to add an enhancement request in Bugzilla. Bugzilla entries are a form of voting by themselves too. snip One should not file stuff in Bugzilla without first looking to see whether it's already there. And this one is: http://d.puremagic.com/issues/show_bug.cgi?id=1003 Stewart.
Re: int or size_t ?
On 07/05/2011 18:09, %u wrote: In Patterns of Human Error, the slide 31 point that you should replce int with size_t why that consider an error ? For those who aren't sure what this is on about: http://www.slideshare.net/dcacm/patterns-of-human-error But the short answer is because dim is a size_t, i needs to cover its range. But = should be = ? Don't you mean ? And the use of a meaningless type alias gets at me. Stewart.
Re: Next Release
On 22/04/2011 20:48, Jonathan M Davis wrote: Well, then I'd better make sure that I get my most recent updates to std.datetime in soon. - Jonathan M Davis Does your library take into account that there's no year 0? Actually, for ISO 8601, which the library follows, there _is_ a year 0. And astronomers have used this year numbering scheme since the 17th century, apparently. Date, DateTime, and SysTime all have the function yearBC which will give you the year as you would normally expect (1 B.C. being immediately prior to 1 A.D. with no year 0). But the ISO standard calls for a year 0, and I followed the standard (it's also way easier to deal with programmatically). So, other than the yearBC function, it treats 0 as the year prior to 1 A.D., and the years prior to 0 are negative. I think most calendar APIs would use 0, -1, -2, etc. to denote 1BC, 2BC, 3BC, etc. because it's by far the easiest thing for both library and library user to work with. And leave to formatting features the task of turning them into BC/AD forms. Look at how my library http://pr.stewartsplace.org.uk/d/sutil/ deals with it. (OK, so it only really manipulates dates in its own linear numbering scheme, but you get the idea.) Stewart.
Re: What are delimited strings good for?
On 10/04/2011 21:51, Jonathan M Davis wrote: snip If that had been `something instead of 'something, _then_ the delimited string becomes useful, but given how rarely backticks are needed, it does seem rather odd to have delimited strings just for that. So, I definitely have to wonder why they exist. I guess for those odd occasions when you want to embed large blocks of text/code in your program and not worry about what characters it may contain, because your choice of delimiting token is too contrived to actually appear in the string. It's probably the same reason that Perl has a similar feature. And I can imagine it having metaprogramming uses. Stewart.
Re: static variables for non-constant expressions?
On 11/04/2011 02:37, Jonathan M Davis wrote: snip I don't know the background of how static variables really work, so is there a good reason why the first function can't work like the one below it? They have to be calculated at compile time so that ordering doesn't matter. If the order mattered, then you get into dependency problems or risk using undefined variables. Languages like C++ and Java have problems with that. snip I recall reading that in C++, static variables are initialised on first call. Which would have to mean that it does something like that internally. But I might be imagining it. I'll have to experiment. Can you give an example of the dependency problems this might lead to? Stewart.
Re: Unicode - Windows 1252
On 16/03/2011 22:17, Tom wrote: I have a D2 code that writes some stuff to the screen (usually runs in cmd.exe pseudo-console). When I print spanish characters they show wrong (gibberish symbols and so, wich corresponds to CP-1252 encoding). Is there a way to convert all outputted streams to CP-1252 without having to wrap writeln function (and replacing all its calls)? My utility library has a console I/O module that converts to/from the console codepage under Windows: http://pr.stewartsplace.org.uk/d/sutil/ See if it's useful to you. I'm not sure whether it works under D2, but it's probably quite straightforward to tweak it so that it does. Stewart.
Re: Read file/stream
On 11/03/2011 18:46, Steven Schveighoffer wrote: snip I am not sure what facilities Phobos provides for reading/writing integers in network order (i.e. Big Endian), but I'm sure there's something. http://www.digitalmars.com/d/1.0/phobos/std_stream.html EndianStream I haven't experimented with it. And I don't expect it to handle structs well. Alternatively, you could use some simple code like version (BigEndian) { uint bigEndian(uint value) { return value; } } version (LittleEndian) { uint bigEndian(uint value) { return value 24 | (value 0xFF00) 8 | (value 0x00FF) 8 | value 24; } } though you would have to remember to call it for each file I/O operation that relies on it. If you use a struct, you could put a method in it to call bigEndian on the members of relevance. Stewart.
Re: Read file/stream
On 11/03/2011 19:50, Ali Çehreli wrote: snip There is also std.intrinsic.bswap Well spotted. I don't tend to look at std.intrinsic much. Presumably there's a reason that it's been provided for uint but not ushort or ulong Stewart.
Re: Read file/stream
On 11/03/2011 21:51, Steven Schveighoffer wrote: snip Presumably there's a reason that it's been provided for uint but not ushort or ulong I think things in std.intrinsic are functions that tie directly to CPU features, True, but... so presumably, the CPU only provides the possibility for 4-byte width. D is designed to run on a variety of CPUs. Do you really think that they all have a built-in instruction to reverse the order of 4 bytes but no other number? Stewart.
Re: Writing an integer to a file
On 07/03/2011 12:11, %u wrote: this is part of the code: Posting the whole code (or even better, a minimal, complete program that shows the problem) helps a lot. void WritePushPop(cmd command, string segment, int index) { string temp = TextFile.Asm; AsmFile = new File(temp, FileMode.OutNew ); string x = toString(index); AsmFile.writeString(@); AsmFile.write(index); File.write writes a binary representation of its argument. To write a textual representation, use writef or writefln. snip Now it wouldn't even build, it doesn't like the line: string x = toString(index); but this line works when I'm working with the console. What's the error message? Stewart.
Re: Win7 64-bit
On 01/03/2011 23:19, Dan McLeran wrote: never mind, i got it. i had to pass the switches: -D -unittest -cov life is hard. it's even harder when you're dumb. Would you care to enlighten the rest of us on what code you were using that requires those extra switches? Stewart.
Re: Pointer to Struct Pointer
On 19/02/2011 13:18, Oliver wrote: Hello, I have the following code that works. What? The code you've posted doesn't work. I'd like to change the t tsData to ts tsData, but this does segfault. The code you've posted throws an AV, and correctly so. If you change tsData to a ts, it runs successfully. At least in 2.051 Windows. Is something different happening on your setup? I do not understand how I dereferece the ts struct correctly. You don't dereference a struct, you dereference a pointer. snip struct rs { int i; union { int intData; //ts tsData; t tsData; }; this( int i, int d, ref int[] data) { this.i = i; this.tsData.d = d; this.tsData.intData = data; } } snip You have not initialised tsData. Consequently, you are trying to dereference a null pointer. Hence the segfault. For it to work with tsData being a pointer, you need to add something like this: this.tsData = new ts; Stewart.
Re: Opt-out polymorphism?
On 13/02/2011 21:34, Sean Eskapp wrote: Is there a way to specify that a function is nonvirtual, but can still be overriden in base classes? e.g. Then you're not overriding at all. You're just declaring a function in the derived class that happens to have the same name. As such, it seems to me to have little use besides writing confusing code. Stewart.
Re: Read non-UTF8 file
On 13/02/2011 21:49, Nrgyzer wrote: snip It compiles and works as long as the returned char-array/string of f.readLine() doesn't contain non-UTF8 character(s). If it contains such chars, writeln() doesn't write anything to the console. Is there any chance to read such files? Please post sample input that shows the problem, and the output generated by replacing the writeln call with writefln(%s, cast(ubyte[]) convertToUTF8(f.readLine())); so that we can see what it is actually reading in. Stewart.
Re: using a binary tree container
On 11/02/2011 12:30, Dominic Jones wrote: snip Would that not be constructing an associated array? Whilst an associated array would do the job, there is no value for the key:value pair, just a list of keys. In the C++ STL there are the set and map containers. I want something like set. Dominic http://pr.stewartsplace.org.uk/d/sutil/ includes a set class template. Stewart.
Re: Verify tuple is a tuple of class objects?
On 18/02/2011 21:22, Steven Schveighoffer wrote: snip template VerifyTuple(Types...) { static if(Types.length == 0) enum bool VerifyTuple = true; else enum bool VerifyTuple == is(Type : Object) VerifyTuple!(Types[1..$]); snip You have two typos there. Corrected version: enum bool VerifyTuple = is(Types[0] : Object) VerifyTuple!(Types[1..$]); But perhaps even nicer: -- template VerifyTuple() { enum bool VerifyTuple = true; } template VerifyTuple(T, Ypes...) { enum bool VerifyTuple = is(T : Object) VerifyTuple!(Ypes); } -- (Some of you will be able to guess what other language I've programmed in in my time from this.) Stewart.
Re: opIn_r not detected
On 10/02/2011 22:32, spir wrote: On 02/10/2011 07:43 PM, Stewart Gordon wrote: snip That got me thinking. It would appear that it auto-dereferences only the left operand. Try adding this to your code and see: writeln(s2 == sp); Works, indeed, but using opEquals on s2, and because s2 is not pointed. In what compiler version/platform? Here's what I get (DMD 2.051, Windows, after fixing the missing import): -- C:\Users\Stewart\Documents\Programming\D\Testsdmd -unittest opin_r.d opin_r.d(19): Error: function opin_r.S.opEquals (ref const(S) s) const is not ca llable using argument types (S*) opin_r.d(19): Error: cannot implicitly convert expression (sp) of type S* to con st(S) -- Or maybe you forgot the -unittest? Stewart.
Re: Assigning Interface to Object
On 16/01/2011 08:23, Jérôme M. Berger wrote: Stewart Gordon wrote: On 15/01/2011 17:44, Steven Schveighoffer wrote: snip Which unnecessarily complicates things. For example, you can't compare two interfaces (try it!). ? interface I {} ... I a = ...; I b = ...; if (a == b) //-- ERROR 1.065: compiles without error, though it seems to be equivalent to is 2.051: it's really weird -- C:\Users\Stewart\Documents\Programming\D\Testsdmd interface_equals.d interface_equals.d(7): Error: function object.opEquals (Object lhs, Object rhs) is not callable using argument types (I,I) interface_equals.d(7): Error: cannot implicitly convert expression (a) of type i nterface_equals.I to object.Object interface_equals.d(7): Error: cannot implicitly convert expression (b) of type i nterface_equals.I to object.Object -- Of course, if the interface declares an opEquals, it's a whole different story Stewart.
Re: Assigning Interface to Object
On 15/01/2011 17:44, Steven Schveighoffer wrote: snip Which unnecessarily complicates things. For example, you can't compare two interfaces (try it!). ?
Re: toDelegate() for D1
On 13/01/2011 17:14, %u wrote: == Quote from Simen kjaeraas (simen.kja...@gmail.com)'s article %ue...@ee.com wrote: I only need something to make a void deleg() from a void func(). This works for me: ReturnType!( F ) delegate( ParameterTypeTuple!( F ) ) toDelegate( F )( F fn ) { return ( ParameterTypeTuple!( F ) args ){ return fn( args ); }; } What am I doing wrong. I can't call the delegate twice with anything in between. Every delegate needs a context pointer. If the function is defined within a function, that context pointer points to the stack frame of the function that defined it. And in this case it uses something from that very stack frame: the parameter fn. ISTM it works straight after you've created it only because the stack frame of toDelegate has not yet been overwritten. However, I'm still puzzled, because the process of calling the delegate ought to itself overwrite the stack frame. You want this: http://pr.stewartsplace.org.uk/d/sutil/ Stewart.
Re: Templated delegate
On 10/01/2011 13:02, Mitja wrote: I would like to have a template which returns appropriate delegate, something like this: For what purpose? All you seem to have is a long-winded identity function. snip and compiled it like this: dmd mod2.d mod1.d, the program would produce segmentation fault. I can't reproduce (DMD 2.051, Windows). In what setup are you experiencing the problem? It works fine when packages in mod2 are omitted. When which packages in mod2 are omitted? I can only make out that this is a compiler bug that needs to be investigated. What would be the correct way for templated delegate? It depends on what you're trying to do. Stewart.
Re: Calling anonymous delegate recursively ?
On 08/01/2011 16:00, Pelle wrote: snip http://en.wikipedia.org/wiki/Fixed_point_combinator#Y_combinator snip How are you getting around D not supporting recursively defined types? Stewart.
Re: Calling anonymous delegate recursively ?
On 08/01/2011 17:40, Andrej Mitrovic wrote: snip Otherwise I'd really like the ability for a lambda to call itself. Perhaps a feature request is in order. I'm not sure what D would gain in practice. If you want a function that calls itself, why not just name the function? Stewart.
Re: undefined identifier getch()
On 08/12/2010 11:06, Nrgyzer wrote: Hey guys, I'm writing a console based tool for windows. To receive the users input, I try to use getch() but the compiler always says Error: undefined identifier getch. When I use getchar() it compiles successfully, but getchar() doesn't returns after a single input. Under DMD 1, getch is declared in std.c.stdio. So import that. Under DMD 2, I don't know why it isn't there. But you just need to add this declaration: extern (C) int getch(); Is there any equivalent version in D for getch? D doesn't have its own API for console operations besides stdin/stdout/stderr stuff. I guess it wasn't worth creating one partly because it would be a load of pointless wrappers around C functions, and partly because in these days where everyone uses GUI-based software they're not used as much. Stewart.
Re: undefined identifier getch()
On 08/12/2010 13:25, Nrgyzer wrote: Okay, but what function can I use to get the pressed key? kbhit/_kbhit seems to do what I want, but hwo can I use it in D? I always get the error, that kbhit (or similar functions) are not available. snip kbhit just tests whether there's a keystroke waiting in the keyboard buffer. It doesn't identify the key pressed. If you want to wait for the user to press a key, use getch. If you want to test whether the user has pressed a key, use kbhit, then use getch to determine what key was pressed. For some reason, this seems to work reliably only on ASCII character keys, backspace, tab and carriage return. But this might be partly due to bugs in the DM implementation. Stewart.
Re: unpacking
On 07/12/2010 17:29, spir wrote: Hello D people, Is there a way to unpack an array into local vars, as: auto x = [1,2,3]; a,b,c = x; import std.stdio; void unpack(A, T...)(out T vars, A data) { assert (vars.length == data.length); foreach (i, v; vars) { vars[i] = data[i]; } } void main() { auto x = [1,2,3]; int a, b, c; unpack(a, b, c, x); writefln(%d %d %d, a, b, c); } Stewart.
Re: array of elements of various subclasses
On 07/11/2010 15:49, spir wrote: snip And I'd like to know, as a possible workaround, if there is a way to save a variadic arg list: class C { ??? xs; this(X xs...) { this.xs = xs; } } What exactly are you trying to do here? If you declare it like that, you are declaring a function that takes a single object of class X, called by passing in the arguments of X's constructor. And in any case, that code won't work, because the object may be allocated on the stack. ISTM what you're really trying to do is this: class C { X[] xs; this(X[] xs...) { this.xs = xs.dup; } } But if all you want to do is return an array, you might as well use a template function: T[] array(T)(T[] data...) { return data.dup; } which you can instantiate either implicitly (for those cases where it works) or explicitly (for other cases). Stewart.
Re: how to initialize immutable 2 dim array
On 31/10/2010 17:10, Michal Minich wrote: I have global static array and I want it to initialize in module constructor, but I get error. I there way to do it without using enum. So you want to initialise it with data acquired at runtime, but make it immutable once initialised? immutable int[5][5] arr; static this () { arr = new int[5][5]; // Error: slice arr[] is not mutable } You have a more fundamental problem here. arr is a static array, so you can't reference-assign it. Best you can do is to either: - initialise it statically, using CTFE or template metaprogramming to do the calculations, if they don't depend on getting external data - use a dynamic array instead, and use .idup to populate it - create a mutable pointer to it in the module constructor int[5][5]* marr = cast(int[5][5]*) arr; and use that to populate the array. But I'm not sure whether this leads to UB, and I still wish the means of casting away const or immutable were explicit. Stewart.
Re: delete an element from an array
On 24/10/2010 12:24, Adam Cigánek wrote: remove removes element at a given offset. I want to remove element with a given value. This is example shows it better: snip Your new example doesn't show it better, it's the only one you've given that shows it at all. What you had originally was auto a = [1, 2, 3, 4, 5, 6]; auto b = delete(a, 4); assert([1, 2, 3, 4, 6] == b); which shows the removal of the element at index 4, not the element with value 4. But there are further questions to be answered: - What do you want it to do if the value isn't in the array? Just return the original array, return a copy of the original array, or throw an exception? - What do you want it to do if the value is in the array more than once? Remove the first, remove the last, remove all of them, or pick one at random? Stewart.
Re: exception types objects
On 19/10/2010 23:23, Jonathan M Davis wrote: snip Perhaps, but there is no real benefit in throwing anything other than an Exception (or Error upon occasion) and if we allow you to throw anything than catch(Exception e) won't catch them all. It also would pretty much violate nothrow since nothrow guarantees that no Exceptions are thrown from that function, and if you can throw any old object anyway... snip Indeed, Nothrow functions do not throw any exceptions derived from class Exception - seems odd to me. I think I've had two uses in my time for throwing something that isn't an Exception: - in a previous version of SDWF, to handle an awkward corner case in the Windows dialog API, though I later found a better way of dealing with it - in the runtime for an Unlambda to D compiler, to serve as the continuation object, though that could just as well be changed I hadn't realised until now that D2 had changed to have a Throwable class and Error and Exception classes derived therefrom. It seems the intention was to prevent a nothrow function throwing anything other than an Error, but it wasn't quite said right. So any solution should probably prevent circumvention by creating a whole new subclass of Throwable. (By a quick look through the Java API docs, checked exception classes are defined as Throwable minus the RuntimeException and Error subclasses.) Stewart.
Re: Copying a delegate
On 19/09/2010 04:35, Jonathan M Davis wrote: snip That doesn't work because you're just copying the pointer. Is there a way to actually do a deep copy of the delegate? I can see why this would be problematic if the delegate had reference types in its scope (since presumably, they'd have to be shallow copied unless you somehow had the equivalent of a copy constructor or postblit constructor for delegates), but even the ability to a do a shallow copy would be better than nothing. Is there any way to do that, or am I out of luck? You mean to duplicate whatever the delegate's context pointer points to? The trouble is that the context pointer could point to either an object or a stack frame. Any code to duplicate a delegate on this basis would need to consider both possibilities. Moreover, a class may or may not provide a dup method, and there's no predictable vtbl slot for it. Things get even more complicated when you realise that occasionally there may be an object allocated on the stack. As such, this would be a complex feature, and IMO unlikely to be implemented. I can't even think of any real practical use for it. Can you? Stewart.
Re: Translation of C function pointer.
On 16/09/2010 15:06, BCS wrote: Hello Steven, // note you can't use void as a parameter type in D void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(/*void*/); pragma(msg, typeof(xDlSym).stringof); outputs: void function() function(sqlite3_vfs*, void*, const const(char*) zSymbol) D, now with C type un-garbleing! Perhaps the only excuse for keeping C-style function pointer declarations in D. But since we have htod, we could just as well use it and leave D free to get rid of this fossil that leads to a syntactic ambiguity. Except that I've just found htod has a bug meaning it rejects this code. Stewart.
Re: Translation of C function pointer.
On 16/09/2010 15:37, Steven Schveighoffer wrote: On Thu, 16 Sep 2010 10:06:24 -0400, BCS n...@anon.com wrote: Hello Steven, // note you can't use void as a parameter type in D void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(/*void*/); pragma(msg, typeof(xDlSym).stringof); outputs: void function() function(sqlite3_vfs*, void*, const const(char*) zSymbol) D, now with C type un-garbleing! I'd have to say, if I wasn't able to use D to do this, it would have taken me hours to figure this one out. Even knowing what it is now, I still can't read it :) snip It took me a moment as well. Basically, the C declaration ReturnType (*Name)(Parameters); becomes in D ReturnType function(Parameters) Name; Where you've got one inside another, you try to apply the same principle. So void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void); starting with the outermost level, you end up with (note (void) becomes ()) void function() (*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); instead of Name, you've got this funny thing. You're left with a function pointer declaration where void function() is the ReturnType, so transforming it again you get void function() function(sqlite3_vfs*, void*, char* zSymbol) xDlSym; or in D2, void function() function(sqlite3_vfs*, void*, const(char)* zSymbol) xDlSym; Whoever wrote the C declaration must have had an even harder job getting it right! I wouldn't have hesitated to use a typedef, if ever I had reason to do C stuff as complicated as this. Stewart.
Re: Formating decimal numbers with commas (1,000.00)
On 14/09/2010 21:00, jicman wrote: Greetings. I have been trying, for more than an hour, to get information on how to format a number (2342.23) to $2,342.23. Just wondering, where have you been searching for this information? I can write a little function to do this, but doesn't format already has this builtin? snip If the documentation http://www.digitalmars.com/d/1.0/phobos/std_format.html is to go by, there doesn't seem to be any such feature, and a quick look through the code doesn't reveal one either. But there are many things std.format doesn't do. I'd imagine that someone's written a more powerful number formatting library module, but I don't know of it. Maybe that someone'll find this thread and enlighten us. Stewart.
Re: String literals have only one instance?
Jonathan Davis wrote: snip You can always check with the is operator though. If it reports true, then the two strings have the same instance. If it reports false, then they don't. I can't see how testing each string literal to see if it's the same instance as another can work. The OP's point is: Are identical string literals *guaranteed* to be the same instance? Regardless of implementation? Regardless of whether they're next to each other, in different modules or anything in between? Regardless of the phase of the moon? Stewart.
Re: string[int[][]] ??
dcoder wrote: == Quote from Steven Schveighoffer (schvei...@yahoo.com)'s article This is what I think you should use: string[int[2]] snip board[[0,0]] = Rook; Further to what others have said, why use strings? There are only 12 possible chess pieces (black and white), plus blank, so probably the most efficient approach is char[8][8] board; and use uppercase letters for white and lowercase for black. This also makes it very easy to embed board positions in code, and to write/read positions to/from a file (but don't forget to validate). But there's something else to consider. Do you want to be able to represent: - whose turn it is to move? - availability of en passant capture? - possibility of castling? (One of my programs uses 'C' to represent a rook on which castling may still be possible, and 'R' for one on which it isn't.) seems to work. thanks. But, the foreach loop looks strange. It looks like it takes the hash value of the key: snip Clearly a bug. Need to investigate further Stewart.
Re: Mixing operations with signed and unsigned types
Ellery Newcomer wrote: On 07/06/2010 07:05 PM, Stewart Gordon wrote: snip Just using uint, of course! For enforcing a non-negative constraint, that is brain damaged. Semantically, the two are very different. So effectively, the edit wars would be between people thinking at cross purposes. I guess it would be interesting to see how many libraries are using unsigned types wherever the value is semantically unsigned, and how many are using signed types for such values (maybe with a few exceptions when there's a specific reason). int i; assert(i = 0); says i can cross the 0 boundary, but it's an error if it does, i.e. programmer doesn't need to be perfect because it *does get caught* (extreme instances notwithstanding). Or equivalently, uint i; assert (i = cast(uint) int.max); uint i; says i cannot cross the 0 boundary, but it isn't an error if it does. programmer needs to be perfect and error doesn't get caught (unless what you're using it for can do appropriate bounds checking). Or the wrapping round is an intended feature of what you're using it for. Comparison - how do you mean? Stewart. Mmmph. Just signed/unsigned, I guess (I was thinking foggily that comparison intrinsically involves subtraction or something like that) But whether subtraction for comparison works doesn't depend on whether the legal ranges of the source values are signed or unsigned, at least as long as they're both the same. What it does depend on is whether the subtraction is performed in more bits than the number required to represent the legal range. Stewart.