Re: Custom Exponents
On 12/14/13 8:22 PM, Malkierian wrote: Alright, so I'm trying to do hex string to integer conversion, but I can't for the live of me find how to do exponent calculation in D. Java has a Math.pow() function that allows you to specify the base and the exponent, but all I've seen in D's libraries are functions that allow you to only specify the exponent and does it on a predetermined base, such as 2, e or 10. I need 16 for the base. http://dlang.org/phobos/std_math.html#.pow See the fourth overload: `if (isFloatingPoint!F isFloatingPoint!G)`. NMS
Re: Building druntime on MAC OS X
On 11/15/13 6:19 PM, Andrew Edwards wrote: I am having little problem building druntime on Mac OS X 10.9 (Mavericks) and am wondering if anyone has experienced with this and some guidance on how to fix it. Here is my command: make -f posix.mak install DMD=../install/bin/dmd And here is the resulting error: ../install/bin/dmd -ofgenerated/osx/default/rdmd rdmd.d ld: unknown option: --export-dynamic clang: error: linker command failed with exit code 1 (use -v to see invocation) --- errorlevel 1 make: *** [generated/osx/default/rdmd] Error 1 -- Regards http://www.akeron.co auto getAddress() { string location = @, period = .; return (info ~ location ~ afidem ~ period ~ org); } Have you tried using this? https://github.com/carlor/dlang-workspace Sorry for the shameless plug. NMS
Re: dub: should we make it the de jure package manager for D?
On Tuesday, 10 September 2013 at 20:48:58 UTC, Andrei Alexandrescu wrote: We've been experimenting with http://code.dlang.org for a while and things are going well. In particular Sönke has been very active about maintaining and improving it, which brings further confidence in the future of the project. We're considering making dub the official package manager for D. What do you all think? Andrei I'm all in favor. Careful about the dependencies though, particularly for dub-registry. It's dependent on userman and vibe-d, which is dependent on openssl, libevent, and libev (in Deimos). NMS
Re: How do you guys debug large programs?
On Monday, 27 May 2013 at 19:55:57 UTC, Gary Willoughby wrote: This is quite an open ended question but i wondered how you guys debug your D programs (i'm talking about stepping through code, setting breakpoints, etc). The lack of nice IDE's with integrated debuggers is worrying when working with D but up until now i haven't need one. Now i've started to write much larger programs, i'm wondering which debuggers do you use? Especially using Linux. I know Alexander Bothe of Mono-D fame is working on debugging support for it: http://mono-d.alexanderbothe.com/?p=997 It's still in alpha, but getting there. NMS
Re: RFC: mysql-native - Supporting both Vibe.d and Phobos sockets
On Sunday, 12 May 2013 at 21:16:33 UTC, Nick Sabalausky wrote: There is need for mysql-native https://github.com/rejectedsoftware/mysql-native to support both Vibe.d's sockets and Phobos sockets. Since Phobos's and Vibe.d's sockets have incompatible APIs, my design converts most of the types in mysql-native into templates. For example, 'Connection' becomes either 'Connection!mySQLSocketVibeD' or 'Connection!mySQLSocketPhobos'. The type 'Command' becomes either 'Command!mySQLSocketVibeD' or 'Connection!mySQLSocketPhobos'. And the same goes for most other types, such as Row, ResultSet, etc. Does incompatible APIs preclude a design like this? - interface MysqlSocket { // ... } class PhobosSocket : MysqlSocket { this(std.socket.Socket _backend) { // ... } // ... } class VibeSocket : MysqlSocket { this(vibe.core.net.TCPConnection _backend) { // ... } } - Sorry if I've overlooked anything obvious, NMS
Re: dtutor.org: a call to action
On Sunday, 5 May 2013 at 19:37:02 UTC, Tyro[17] wrote: The main contributors of D are doing a wonderful job of enhancing the language. I can confidently say that we are leagues ahead of where we stood a just two years ago. But there has been a long cry for documentation that has gone unanswered: not because they refuse to cooperate but rather, because they are a small volunteer force, occupied by real demands to address the quirks of the language, and lack the time to all issues by themselves. Don't we all :( It stands then that the community can make a conscious effort to address some of the outstanding issues. As such, I have chosen to champion the tutorial/documentation effort. Though, I possess very little programming experience but am willing to try and am hereby soliciting your assistance in making this a reality. Good luck! dtutor.org is an active domain dedicated to providing tutorials for the language. I will require content contributors but before we can begin to provide content there are a couple of issues to address: I. Features to be supported Interactive Tutorials - Users must be able to modify and execute examples in place to observe side effects. You have DPaste to work with here (http://dpaste.dzfl.pl/), IIRC it is connected to sample code at dlang.org. Interactive Books - A number of free books exist around the internet that can be ported to D. The first two that come to mind are How to Think Like a Computer Scientist, Problem Solving with Algorithms and Data Structures Using Python and Ali Çehreli's very own Programming in D. Videos are useful as well. Problems - Staged ICPC problems for users to attempt. Solutions may be submitted online for comparison against previously submitted solutions to determine efficiency ranking and users may choose to create and account to keep track of progress. Online Judge - to be used to determine accuracy and efficiency of submitted solutions to problems and planned programming contests. I've had good experiences learning via stuff like that. Forum - Unlocked to individual users per problem after solution accepted by Online Judge. Rejected Software (creators of vibe) has vibenews, which I believe is quite customizable. II. Look and Feel Look and feel of the site will be largely influenced by two things: The DConf website and this little gem which provides encouragement for the ideas behind interactive tutorials/books: Runestone (https://github.com/bnmnetp/runestone); I came across it while searching for ideas on how to get started with dtutor.org and must admit: it is a fascinating little project. It is! I have to vouch for cplusplus.com, which isn't interactive, but I was able to teach myself C++ with only that and C++ for Dummies, so it worked for one guy. I am wondering if there are any Python experts (or experts in general) out there willing to assist in porting it to D? It comes with built in support for Python and C/C++ among other languages. However, because dtutor.org aims to promote all things D, it would aid greatly to have a D implementation which removes all external dependencies and support vice implementing D support for the original project. By doing this we can showcase the strengths of DMDScript, vibe and other technology already available in D. Logo: My idea for the logo is simply this (see attachment): D!(tutor).org If your target audience is people who know little about D, this would just look odd. As Andrei would say: destroy! III. Constraints DMDScript for web scripting Vibe for hosting (diet templates) MangoDB for database IV. Timeline The hope is for complete functionality by DConf 2014. Shooting for Initial Launch by September. Calling all website designers, database developers, authors and D enthusiast. Lend a hand in eliminating this problem. Like everyone, my time is limited, but I can help a bit. Sign me up! Andrew NMS
Re: dtutor.org: a call to action
On Sunday, 5 May 2013 at 22:06:17 UTC, Nathan M. Swan wrote: On Sunday, 5 May 2013 at 19:37:02 UTC, Tyro[17] wrote: The main contributors of D are doing a wonderful job of enhancing the language. I can confidently say that we are leagues ahead of where we stood a just two years ago. But there has been a long cry for documentation that has gone unanswered: not because they refuse to cooperate but rather, because they are a small volunteer force, occupied by real demands to address the quirks of the language, and lack the time to all issues by themselves. Don't we all :( It stands then that the community can make a conscious effort to address some of the outstanding issues. As such, I have chosen to champion the tutorial/documentation effort. Though, I possess very little programming experience but am willing to try and am hereby soliciting your assistance in making this a reality. Good luck! dtutor.org is an active domain dedicated to providing tutorials for the language. I will require content contributors but before we can begin to provide content there are a couple of issues to address: I. Features to be supported Interactive Tutorials - Users must be able to modify and execute examples in place to observe side effects. You have DPaste to work with here (http://dpaste.dzfl.pl/), IIRC it is connected to sample code at dlang.org. Interactive Books - A number of free books exist around the internet that can be ported to D. The first two that come to mind are How to Think Like a Computer Scientist, Problem Solving with Algorithms and Data Structures Using Python and Ali Çehreli's very own Programming in D. Videos are useful as well. Problems - Staged ICPC problems for users to attempt. Solutions may be submitted online for comparison against previously submitted solutions to determine efficiency ranking and users may choose to create and account to keep track of progress. Online Judge - to be used to determine accuracy and efficiency of submitted solutions to problems and planned programming contests. I've had good experiences learning via stuff like that. Forum - Unlocked to individual users per problem after solution accepted by Online Judge. Rejected Software (creators of vibe) has vibenews, which I believe is quite customizable. II. Look and Feel Look and feel of the site will be largely influenced by two things: The DConf website and this little gem which provides encouragement for the ideas behind interactive tutorials/books: Runestone (https://github.com/bnmnetp/runestone); I came across it while searching for ideas on how to get started with dtutor.org and must admit: it is a fascinating little project. It is! I have to vouch for cplusplus.com, which isn't interactive, but I was able to teach myself C++ with only that and C++ for Dummies, so it worked for one guy. I am wondering if there are any Python experts (or experts in general) out there willing to assist in porting it to D? It comes with built in support for Python and C/C++ among other languages. However, because dtutor.org aims to promote all things D, it would aid greatly to have a D implementation which removes all external dependencies and support vice implementing D support for the original project. By doing this we can showcase the strengths of DMDScript, vibe and other technology already available in D. Logo: My idea for the logo is simply this (see attachment): D!(tutor).org If your target audience is people who know little about D, this would just look odd. As Andrei would say: destroy! III. Constraints DMDScript for web scripting Vibe for hosting (diet templates) MangoDB for database IV. Timeline The hope is for complete functionality by DConf 2014. Shooting for Initial Launch by September. Calling all website designers, database developers, authors and D enthusiast. Lend a hand in eliminating this problem. Like everyone, my time is limited, but I can help a bit. Sign me up! Andrew NMS I forgot, do you have a github repo up? NMS
Re: dtutor.org: a call to action
On Sunday, 5 May 2013 at 20:27:57 UTC, Andrei Alexandrescu wrote: Would be great to showcase a site using runestone (I browsed the README real quick without finding one). interactivepython.org
embd 0.1.0 - embedded D
Announcing the release of embd, a low-level (i.e. small) API for embedding D code into text: https://github.com/carlor/embd It's a bit of an inconvenient API, but it's customizable and gives the client control in what gets passed to the template. I hope some of you find it useful! NMS
Re: embd 0.1.0 - embedded D
On Wednesday, 6 March 2013 at 11:29:51 UTC, Sönke Ludwig wrote: Am 06.03.2013 10:08, schrieb Nathan M. Swan: Announcing the release of embd, a low-level (i.e. small) API for embedding D code into text: https://github.com/carlor/embd It's a bit of an inconvenient API, but it's customizable and gives the client control in what gets passed to the template. I hope some of you find it useful! NMS Great, finally something that works for plain text files! I guess a simple wrapper could make it work with a similar interface to vibe.d's Diet templates (slightly ugly with that struct because of the additional range template argument and not tested at all): struct renderEmbd(string FILE, ALIASES...) { class Context(R) : emdb.Context { R* _output; mixin(renderer); void write(string content, dchar evalCode){ if (evalCode == '=') filterHtmlEscape(*_output, content); else _output.put(content); } } static void opCall(R)(ref R output_range) { static Context!R ctx; if( !ctx ) ctx = new Context!R; ctx._output = output_range; scope(exit) ctx._output = null; ctx.render!(import(FILE), `!=`, `%`, `%`)(); } } Usage: auto dst = appender!string(); renderEmbd!(userprofile.embd.html, username, title, biography)(dst); Yes, my original intent was to use it in vibe.d projects. Should I try to adopt it into vibe.d? NMS
Re: The new std.process is ready for review
Jonathan M Davis wrote: On Saturday, February 23, 2013 18:39:10 H. S. Teoh wrote: Alternatively, I would push for renaming the old std.process to something like old.process (or something else), which is much less of a breakage than deleting it from Phobos outright -- existing code just need to have their imports fixed and will continue working, whereas deleting the module outright leaves existing code with no recourse but to potentially rewrite from scratch. This may be easier to convince Walter Andrei on, than outright killing old deprecated modules. Possibly, but Walter takes a very dim view on most any code breakage, even if it means simply changing a makefile to make your code work again, so I'd be very surprised if he thought that moving the current std.process would be acceptable. If Andrei could be convinced, then we could probably do it, but I wouldn't expect him to agree, and IIRC, he had no problem with the std.process2 scheme and might even have suggested it. So, I suspect that your only hope of avoiding std.process2 is if you can come up with a better name. - Jonathan M Davis Why not just deprecate everything currently in std.process and drop in the new stuff? It might be a bit ugly, but it prevents both code breakage _and_ a proliferation of std.module2s. My 2 cents, NMS
Re: vibe.d 0.7.12 released
On Monday, 11 February 2013 at 21:41:33 UTC, Jacob Carlborg wrote: On 2013-02-11 22:07, FG wrote: The problem I have with those is that they are designed for HTML. What if I wanted to make an email template instead? Erb is like a Ruby preprocessor that can be used for any format. It's used for many things in Ruby on Rails: index.html.erb - Erb preprocessor, result is HTML % if foo % liasd/li % end % bar.js.coffee.erb - Erb then CoffeeScript preprocessor, result is JavaScript % if foo % bar = - console.log(asd) % end % foo.text.erb - Erb preprocessor, result is plain text % if foo % asd % end % database.yml.erb - Erb preprocessor, result is YAML development: username: %= username % password: %= password % This really makes sense for D. It can be easily combined with D's mixin capabilities to make it so you don't even need to implement stuff like various loops: % [d code] % - [d code] %= [d expr] % - buffer.write([d expr]); [text]- buffer.write([text]); NMS
Re: drop html docs from the dmd distribution?
On Monday, 4 February 2013 at 00:26:06 UTC, FG wrote: On 2013-02-04 00:58, Walter Bright wrote: They seem rather pointless, considering: 1. them being on the web is better anyway 2. the new pdf version of the spec Theoretically: It's useful, because the docs' version matches the compiler, while the website only lists current documentation. Practically: I'm quite sure few people read those offline html docs. I do, when I have no internet access. NMS
Re: @property - take it behind the woodshed and shoot it?
On Thursday, 24 January 2013 at 08:35:01 UTC, Walter Bright wrote: This has turned into a monster. We've taken 2 or 3 wrong turns somewhere. Perhaps we should revert to a simple set of rules. 1. Empty parens are optional. If there is an ambiguity with the return value taking (), the () go on the return value. 2. the: f = g rewrite to: f(g) only happens if f is a function that only has overloads for () and (one argument). No variadics. 3. Parens are required for calling delegates or function pointers. 4. No more @property. What about code that's always ignored @property? int delegate() _del; int delegate() getDelegate() { return _del; } auto del = getDelegate(); // does _del get called? Just a thought, NMS
Re: dmd json file output
On Wednesday, 23 January 2013 at 20:02:36 UTC, Jacob Carlborg wrote: On 2013-01-23 18:09, Timon Gehr wrote: That still requires at least one of two secondary parsers. Technically yes, but there's already a demangler available in Phobos/druntime. Not every program using the json output will be in D (especially IDEs). NMS
Re: Operator overloading question
On Monday, 21 January 2013 at 06:19:47 UTC, Joseph Cassman wrote: Please refer to http://dpaste.dzfl.pl/edit/b73ef2cd The code is contrived but is trying to focus on overloading the + and * operators for a struct. Here is the output. /home/c215/c527.d(36): Error: incompatible types for ((x) + (y)): 'Arithmetic!(int)' and 'Arithmetic!(int)' /home/c215/c527.d(37): Error: 'x' is not of arithmetic type, it is a Arithmetic!(int) /home/c215/c527.d(37): Error: 'y' is not of arithmetic type, it is a Arithmetic!(int) I am trying to understand why there are errors at all. Also why the error for line 36 is different from the error for line 37. Thanks Joseph The correct keyword is opBinary, not opbinary. Also, that's a link to editing the paste, viewing it is: http://dpaste.1azy.net/b73ef2cd
Re: parallel() and random number generation
On Monday, 14 January 2013 at 22:24:22 UTC, Joseph Rushton Wakeling wrote: Hello all, One of the claims made for pseudo-random number generation in D is that rndGen (default RNG) is thread-safe, that is, each instance is unique to its thread and is seeded with unpredictableSeed, which should strongly limit the chances of two threads having correlated sequences of pseudo-random numbers. Now consider the following code: import std.random, std.range, std.stdio; void main() { rndGen.seed(1001); foreach(i; iota(12)) writeln(uniform(0.0, 1.0)); } Obviously, because we seed rndGen, this produces exactly the same sequence every time. But now suppose we use a parallel foreach: import std.parallelism, std.random, std.range, std.stdio; void main() { rndGen.seed(1001); foreach(i; iota(12).parallel()) writeln(uniform(0.0, 1.0)); } Now, I'd expect that suddenly a number of the random variates would suddenly become unpredictable with each run, and that the number thereof would be proportional to the number of threads -- so with 2 threads, we'd expect half the numbers to suddenly be unpredictable with each run -- because only one thread would be using the seeded pseudo-random sequence, and the others would be using a separate rndGen with unpredictable seed. But actually, in my experience, the number of random variates that differ from the predictable sequence is not in proportion to the number of threads and often corresponds only to the last 3-4 variates. This is a bit worrying, because it raises the question of whether the same rndGen is being used in the different threads, and thus whether in fact threads might generate correlated random sequences. Advice/thoughts/explanations? Thanks best wishes, -- Joe It's thread-safe when you use std.concurrency; std.parallelism is _not_ really safe at all. NMS
Proposal: DPM, the D Package Manager
Here's my proposal for a D Package Manager. I want to make sure it has a good design before I write any code, so here it is: http://wiki.dlang.org/User:Nathan_M._Swan/DPM_Proposal I know there are many gaps in this, I want to see which are the most important to fill. I plan to make a central CPR in addition to the dpm program. Thanks in advance for your feedback! NMS
Re: Better forum
On Thursday, 6 December 2012 at 18:55:19 UTC, Andrei Alexandrescu wrote: On 12/6/12 1:47 PM, Nick Sabalausky wrote: This one isn't. Neither is Vibe.d's: http://news.rejectedsoftware.com What do they use? Andrei Vibenews, kinda like this forum: http://registry.vibed.org/view_package/vibenews It is both an HTTP and NNTP server. NMS
Re: MS ODBC encoding issue
On Tuesday, 4 December 2012 at 07:59:40 UTC, Sam Hu wrote: Greetings! Any help would be much appreicated in advance as I've really struggled for quite long time! I wrote a class wrapper for MS ODBC Access database.When I try to run query on an Access database file,all fields contains English character are fine with the result,but for those Asian characters like Chinese,the result shows blank in DFL gui form and shows mess (unrecognizable under console).I think maybe the problem is in the fetchAll function which I provided as below together with the other main parts of the class: Client code (DFL form): [code] protected void onReadClick(Object sender,EventArgs e) { Odbc odbc=new Odbc; odbc.connect(artistdb,,); if(!odbc.isOpen) { throw new Exception(Failed to connect to ODBC); return; } auto record=odbc.fetchAll(select * from artists where artistid=~txtSearch.text~;); txtID.text=to!string(record[0][0]); txtName.text=to!string(record[0][1]); odbc.close; } [/code] ODBC wrapper class: [code] SQLRETURN SQLExecDirectUTF8(SQLHSTMT stmt,string text,SQLINTEGER tl) { SQLRETURN retcode; //uint16* utf16=UTF8toUTF16(text,null); retcode=SQLExecDirectW(stmt,cast(SQLWCHAR*)toUTF16z(text),tl); return retcode; } string[][] fetchAll(const char* pszSql) { string[][] v; if(pszSql is null ) return null; retCode=SQLExecDirectUTF8(hStmt,to!string(pszSql),SQL_NTS); if((retCode != SQL_SUCCESS) (retCode != SQL_SUCCESS_WITH_INFO)) { throw new Exception(format(Error AllocHandle with retCode: %d,retCode)); return null; } retCode=SQLNumResultCols(hStmt,col); if((retCode != SQL_SUCCESS) (retCode != SQL_SUCCESS_WITH_INFO)) { throw new Exception(format(Error AllocHandle with retCode: %d,retCode)); return null; } row=0; SQLINTEGER colLen = 0; SQLSMALLINT buf_len = 0; SQLINTEGER colType = 0; while(true) { char sz_buf[256]; char* pszBuf; SQLINTEGER buflen; string[] rowData=new string[col+1]; if(SQLFetch(hStmt)==SQL_NO_DATA) { break; } for(int i=1;i=colCount;i++) { SQLColAttribute(hStmt, cast(ushort)i, SQL_DESC_NAME, sz_buf.ptr, 256, buf_len, cast(void*)0); SQLColAttribute(hStmt, cast(ushort)i, SQL_DESC_TYPE, cast(void*)0, 0, cast(short*)0, colType); SQLColAttribute(hStmt, cast(ushort)i, SQL_DESC_LENGTH, null, 0, cast(short*)0, colLen); pszBuf=cast(char*)(new char[colLen+1]); //pszBuf[0]='\0'; SQLGetData(hStmt,cast(ushort)i,SQL_C_CHAR,pszBuf,50,cast(int*)buflen); pszBuf[buflen]='\000'; rowData[i-1]=to!string(pszBuf); } v~=rowData; row++; } SQLCancel(hStmt); return v; } string[][] fetchAll(string sql) { return fetchAll(sql.ptr); } [/code] I've never used ODBC before, but a quick scan of the MSDN docs suggests that you should use SQL_C_WCHAR instead, maybe using some D wstring functions too. BTW, convert sql.ptr - std.string.toStringz(sql); this is good practice, though I'm not sure it's your problem. NMS
Re: dmd demangling
On Thursday, 22 November 2012 at 08:00:41 UTC, Brad Roberts wrote: On 11/21/2012 10:36 PM, Nathan M. Swan wrote: We can't post to dmd-internals anymore, so I assume I should post here. Um... what? The list hasn't changed configs since it was setup. Anyone can subscribe, all new members go through moderation once (robots that are smart enough to subscribe do occasionally show up) and afterwards it's wide open. What issues are you seeing? Oh, it's a mailing list. It didn't show up as a newsgroup in Thunderbird, and posting didn't work at the web frontend, and I'd read somewhere that it was only to be used for the automatic commit logs. Sorry about that. NMS
dmd demangling
We can't post to dmd-internals anymore, so I assume I should post here. Is there any demangle function in the dmd code, or should I write my own? (I'm working on automatic demangling for linker error messages) Thanks, Nathan M. Swan
Re: Bulding latest DMD and associated projects from github master
On Monday, 19 November 2012 at 00:40:10 UTC, Rob T wrote: First I cloned everything from github master, and that went well but I'm now encountering a lot of silly stumbling blocks due to inadequate documentation, for example it's clear how to build anything - period. There may be documentation somewhere(?), but all I could find was this external blog post http://xtzgzorex.wordpress.com/2011/07/31/d-building-dmd-and-phobos-on-linux/ The instructions in the blog allowed me to successfully build DMD src with 64-bit arch on Linux. So far so good, but I'm sure this is not the end of the problems I'll encounter. Being new to this, I'll know immediately where the documentation is failing, so as I get stuck and unstuck I'm in a good position to create missing documentation or improve on the current documentation. If I'm to try and contribute, I have a few questions, for example can anyone contribute at this level (build process)? If I am allowed to contribute, then what's the process for making contributions? Thanks. --rt Check this out: https://github.com/carlor/dlang-workspace
Re: UDAs - Restrict to User Defined Types?
On Wednesday, 7 November 2012 at 23:18:41 UTC, Walter Bright wrote: Started a new thread on this. On 11/7/2012 3:05 AM, Leandro Lucarella wrote: OK, that's another thing. And maybe a reason for listening to people having more experience with UDAs than you. For me the analogy with Exceptions is pretty good. The issues an conveniences of throwing anything or annotating a symbol with anything instead of just type are pretty much the same. I only see functions making sense to be accepted as annotations too (that's what Python do with annotations, @annotation symbol is the same as symbol = annotation(symbol), but is quite a different language). There's another aspect to this. D's UDAs are a purely compile time system, attaching arbitrary metadata to specific symbols. The other UDA systems I'm aware of appear to be runtime systems. This implies the use cases will be different - how, I don't really know. But I don't know of any other compile time UDA system. Experience with runtime systems may not be as applicable. Another interesting data point is CTFE. C++11 has CTFE, but it was deliberately crippled and burdened with constexpr. From what I read, this was out of fear that it would turn out to be an overused and overabused feature. Of course, this turned out to be a large error. One last thing. Sure, string attributes can (and surely would be) used for different purposes in different libraries. The presumption is that this would cause a conflict. But would it? There are two aspects to a UDA - the attribute itself, and the symbol it is attached to. In order to get the UDA for a symbol, one has to look up the symbol. There isn't a global repository of symbols in D. You'd have to say I want to look in module X for symbols. Why would you look in module X for an attribute that you have no reason to believe applies to symbols from X? How would an attribute for module X's symbols leak out of X on their own? It's not quite analogous to exceptions, because arbitrary exceptions thrown from module X can flow through your code even though you have no idea module X even exists. In module sql.d: /// For every field marked [serialize], add to table void saveToDatabase(T)(DBConnection db, T model); In module json.d: /// For every field marked [serialize], add to JSON object string jsonSerialize(T)(T obj); In module userinfo.d: [dbmodel] struct UserModel { [serialize] string username; // What do you do if you want this in the database, but not the JSON? string password; [serialize] Content ownedContentOrWhateverThisWebsiteIs; } The only solution to this question is to differentiate db_serialize and json_serialize; looks a lot like C, doesn't it? My suggested soluion: @annotation (with [] UDA syntax): module sql; @annotation enum model; @annotation enum serialize; module json; @annotation enum serialize; module userinfo; import sql, json; [sql.model] struct UserModel { [sql.serialize, json.serialize] string username; [sql.serialize] string password; [sql.serialize, json.serialize] Content content; } My thoughts, NMS
Re: deprecate deprecated?
On 11/06/2012 10:03 PM, monarch_dodra wrote: On Tuesday, 6 November 2012 at 23:56:13 UTC, Walter Bright wrote: I know there's been some long term unhappiness about the deprecated attribute - it's all-or-nothing approach, poor messages, etc. Each change in it changes the language and the compiler. I *just* had a conversation about this, but there *needs* to be a way to to tell the compiler: don't use deprecated stuff: If it merely issues a warning, then you'll end up calling deprecated code, because traits will answer positively to something that is actually deprecated: For example if a range has deprecated opIndex, and you try a search on that range, the implementation will take the RA road... I had proposed a three state -d: -- : Deprecated stuff just can't be used -d : You can use deprecated stuff, but you get no warning -dw : You can use deprecated stuff, and are served with a warning I'm in favor of this; we can stop filling Phobos with scheduled for deprecation, and just deprecate things. People using e.g. std.xml would get warnings but not have to refactor all their code at once. NMS
Re: [ ArgumentList ] vs. @( ArgumentList )
On 11/06/2012 10:18 AM, Walter Bright wrote: For User Defined Attributes. In the north corner we have the current champon: --- [ ArgumentList ] Pros: precedent with C# looks nice Cons: not so greppable parsing ambiguity with [array literal].func(); -- In the south corner, there's the challenger: @( ArgumentList ) Pros: looks like existing @attribute syntax no parsing problems Cons: not as nice looking -- No hitting below the belt! Let the games begin! [], because @ should be reserved for future language keywords. Whenever people post suggested language features that require some marking, they introduce a new @attribute, because introducing a plain keyword breaks code. If you have @UDAs, this further limits language expansion. Example: let's say you want to introduce a nogc mark: 1. Not a nogc keyword, that could break bool nogc; 2. If you have @, @nogc could break an enum nogc; attribute. 3. Now you're stuck with __nogc or #nogc or something uglier. There is a familiar-to-other-langauges advantage to @, but there is a better-than-other-languages advantage to []. My thoughts, NMS
Re: Multidimensional slicing
On Wednesday, 24 October 2012 at 14:25:33 UTC, Joseph Rushton Wakeling wrote: Hello all, Suppose I have some data in an 2-dimensional associative array (it could be larger dimension, but let's limit it to 2d for now). I'm using an associative array because the underlying data is sparse, i.e. for any given index pair (i, j) there's most likely not an entry. It's trivial to take a slice of this data using the first dimension, i.e. if a[i][j] gives the value for the key pair (i, j), a[i] will give the array of values for all values of j, and a[i].keys will give me all the values of j that are connected to i. ... however, I can't do this the opposite way, i.e. to slice it a[][j] -- I get an error message, e.g.: Error: ulong[ulong][ulong] cannot be sliced with [] and similarly there is no way to identify a[][j].keys i.e. all the i indexes associated with j. So, I'm curious: is there any practical way to slice across the 2nd (or higher) dimension in this way, so that I get access to both values and keys? The application here is a large (but sparse) dataset of links forming a bipartite graph of user-object weighted links. The goal would be for the 2d array to store those weights, and the slices would allow you to look at that collection from one of two viewpoints -- i.e. all the objects a given user is linked to, or all the users a given object is linked to. Of course, it's trivial to have two associative arrays, say userLinks and objectLinks, where the keys are respectively object and user IDs and the values are the weights, but that means storing the weight values twice. I'd like to be able to have one entity that stores the links and weights, and which can be sliced either way without needing to copy data and without any added CPU overhead (the planned simulation and data sizes are large, so something that is costly CPU-wise or that requires additional allocation is unlikely to scale). Thanks in advance for any advice, Best wishes, -- Joe Short answer: no. Long answer: It would be inefficient to create a slice like you ask if your data structure is associative arrays. Here's the code: ulong[] result; foreach(i, js; a) { foreach (j, w; js) { if (j == jYouAskedFor) { result ~= w; } } } // use result... The worst case here is O(n), where n is the number of links. The slicing of a[i] is O(1). The two associative arrays is probably your best bet, but I'm no expert on this. Hope it helps, Nathan M. Swan
Linking with phobos on compiled dmd, osx 64bit
Hello all! I've been hacking on dmd, and something hasn't been working. This is how I compile it: cd dmd/src make -f posix.mak cd ../../druntime make -f posix.mak cd ../phobos make -f posix.mak MODEL=64 cp generated/osx/release/64/libphobos2.a /usr/local/lib/ cd ../dmd/src ./dmd file.d This is the error I get: ld: warning: ignoring file /usr/local/lib/libphobos2.a, file was built for archive which is not the architecture being linked (i386) Undefined symbols for architecture i386: _main, referenced from: start in crt1.10.6.o (maybe you meant: _D4file7no_mainFAAyaZv) _D3std5stdio12__ModuleInfoZ, referenced from: _D4file12__ModuleInfoZ in file.o _D3std5stdio6stdoutS3std5stdio4File, referenced from: _D3std5stdio16__T7writelnTAyaZ7writelnFAyaZv in file.o _D15TypeInfo_Struct6__vtblZ, referenced from: _D47TypeInfo_S3std6traits15__T8DemangleTkZ8Demangle6__initZ in file.o _D3std9exception7bailOutFNaNfAyakxAaZv, referenced from: _D3std9exception14__T7enforceTbZ7enforceFbLAxaAyakZb in file.o Any ideas on what's wrong? Thanks, NMS
Re: is array an InputRange?
On Friday, 5 October 2012 at 13:39:56 UTC, ref2401 wrote: import std.range; int[] numbers = [1, 3, 5, 7, 9, 11]; auto rangeObject = inputRangeObject(numbers); auto inputRange = cast(InputRange!(int[]))rangeObject; why does 'inputRange' equal null? Suggested reading: http://ddili.org/ders/d.en/ranges.html Forget about the std.range objects. NMS
Re: classes structs
On Thursday, 20 September 2012 at 01:42:26 UTC, David Currie wrote: On Tuesday, 18 September 2012 at 18:42:33 UTC, Timon Gehr wrote: On 09/18/2012 07:07 AM, David Currie wrote: [ALL CAPS] It does not matter who is the loudest guy in the room. If you have a point to make, just make it. (Stating the conclusion is not making a point. Skipping forward and predicting polite refusal does not help.) Most of the statements in the OP are inaccurate. The best way to get in touch with the language is by reading the online documentation and by experimenting with the compiler (prepare for some bugs and unspecified corner cases). Reading the newsgroup helps too. Usually it is best to double-check any claims about the language expressed online, using the reference implementation. Apologies for SHOUTING. I am unfamiliar with forum syntax and etiquette I merely wished *stressing* some words. What is OP and perhaps why are most statements inaccurate? How does one get to the newsgroups. I only got here because Walter gave me a link. I would gratefully welcome links. OP = Original Post(er). They use a lot of abbreviations I don't know here: acronymfinder.com is your friend. The only inaccurate statement I noticed was that class constructors are called (null is the default). NMS
Re: Running unittests in a D library
On Wednesday, 19 September 2012 at 18:49:12 UTC, Chris Molozian wrote: Hey all, I'm sure that this is a rather daft question but I've tried to search the d.learn mailing list and must have missed a question about it. I've read the unit testing documentation on dlang.org and I know that `unittest { /* some code */ }` blocks are compiled into the executable and executed after static initialization and before the main() function is called. This makes sense in an application but how does this apply to a library? For example, writing a D library using DMD's `-lib` compiler flag, how do I run the unit tests in the generated library? Cheers, Chris $ rdmd --main -unittest (other compiler flags) (source files)
Re: GC vs. Manual Memory Management Real World Comparison
On Wednesday, 5 September 2012 at 11:03:03 UTC, Benjamin Thaut wrote: I rewrote a 3d game I created during my studies with D 2.0 to manual memory mangement. If I'm not studying I'm working in the 3d Engine deparement of Havok. As I needed to pratice manual memory management and did want to get rid of the GC in D for quite some time, I did go through all this effort to create a GC free version of my game. The results are: DMD GC Version: 71 FPS, 14.0 ms frametime GDC GC Version: 128.6 FPS, 7.72 ms frametime DMD MMM Version: 142.8 FPS, 7.02 ms frametime GC collection times: DMD GC Version: 8.9 ms GDC GC Version: 4.1 ms As you see the manual managed version is twice as fast as the garbage collected one. Even the highly optimized version created with GDC is still slower the the manual memory management. You can find the full article at: http://3d.benjamin-thaut.de/?p=20#more-20 Feedback is welcome. Kind Regards Benjamin Thaut Did you try GC.disable/enable?
Re: The best programming advice I ever got
On Wednesday, 29 August 2012 at 14:53:39 UTC, Andrei Alexandrescu wrote: Not directly related to D, but hopefully a hook :o). http://www.informit.com/articles/article.aspx?p=1945828 Andrei Great article. Learning to learn is really what distinguishes vocational training from true education. NMS
Re: best practices tutorial needed (for function signature, class vs struct, etc)
On Saturday, 25 August 2012 at 20:37:27 UTC, timotheecour wrote: Is there a best practices page on this site to use as reference for those FAQ, that AFAIK are not in the docs: * when to use class vs struct (eg http://stackoverflow.com/questions/11058906/struct-vs-class-for-writing-d-wrappers-around-foreign-languages) General rule I follow (don't know if this is common): use `struct` unless you are using pointers a lot: that's a sign you need classes. * what's the standard signature for opEquals () (ef http://forum.dlang.org/thread/ewhhutwupqxbepqyz...@forum.dlang.org#post-mailman.1402.1345925314.31962.digitalmars-d:40puremagic.com) * same for toString(), this(), etc. IDK * to use or not to use @property @property is semantically a fake field. Thus, use it to get an attribute that doesn't have side effects (except for setters) and runs in constant time. etc.. I understand it's on a case by case but I would hope there are certain rules one can follow in 99% cases. My 0.02 dollars, NMS
Re: Consistency, Templates, Constructors, and D3
On Friday, 24 August 2012 at 05:14:39 UTC, F i L wrote: We replace it with special factory functions. Example: class Person { string name; uint age; this new(string n, uint a) { name = n; age = a; } } void main() { auto philip = Person.new(Philip, 24); } Notice 'new()' returns type 'this', which makes it static and implicitly calls allocation methods (which could be overridden) and has a 'this' reference. The constructor definition syntax doesn't seem to be an improvement: this new instead of the old this. The constructor calling syntax is actually something I've thought of before. I think Class.new is better than new Class, simply because it's more succinct when chaining: Class.new().method() vs. (new Class()).method() NMS
Re: Exception programming difficult
On Sunday, 12 August 2012 at 03:02:50 UTC, Marco Leise wrote: I just got a bit frustrated and wanted to say that I like working with Exceptions in Java a lot more. I don't. When writing a simple command line program, when there's an error, it usually means the user messed up and I can't recover. I just print the message and terminate. I don't want to have to write throws Exception for everything. void main(string[] args) { try { realMain(args); return 0; } catch (Exception e) { stderr.writeln(e.msg); } } The idea sounds nice, but it's annoying in practice. The point of exceptions is to _centralize_ error handling. Being forced to either catch or declare is almost as bad as C-style errno error handling. Perhaps an annotation might be nice, as long as it doesn't force catching: void buggyFunction(string file, int exception) @throws(StdioException);
Re: Exception programming difficult
On Monday, 13 August 2012 at 10:02:23 UTC, Marco Leise wrote: Thoughts ? I like this idea - you can use checked exceptions, but you aren't forced. Though I think private and free functions should by default just use @throws(Exception). Not using @throws is like saying I don't pay attention to what errors might occur, a new version might be different. NMS
Re: Convert little imperative code to functional coding style
On Friday, 10 August 2012 at 18:26:56 UTC, Timon Gehr wrote: Is this what you are looking for? import std.stdio; import std.range: iota; import std.algorithm: map, filter, joiner; import std.typecons : tuple; import std.math : sqrt, floor; void main(){ immutable limit = cast(size_t)floor(sqrt(1_000.0)); auto r = iota(2,limit).map!(m=iota(1,m-1).map!(n=tuple(m,n))).joiner .filter!(t=2*t[0]*(t[0]+t[1])==1_000) .map!(t=(t[0]^^4-t[1]^^4)*(2*t[0]*t[1])); writeln(r.front); } Ugh! I guess functional isn't always the best ;)
Re: What would need to be done to get sdc.lexer to std.lexer quality?
On Thursday, 2 August 2012 at 07:22:57 UTC, Bernard Helyer wrote: Gonna spend some time massaging this into a Walter-Approved (tm) lexer. It's got some ways to go. Are there any specific ways I could help? NMS
Type safety + auto = win!
A story: Playing around with functional programming, I started trying to implement interesting functions in Lisp. It all went well until permute, a function which isn't that complicated but involves lists, lists of lists, and lists of lists of lists. This was so confusing and complicated that I gave up. More recently, I tried it again in Haskell. It took less than twenty minutes! The reason was Haskell's type declarations, which made it so much easier to think about what was going in and out. How this relates to D: The type system can often get annoying, and become a pain (e.g. Java), hence the popularity of dynamic typing (Python/Ruby/Ecmascript). But when thinking about complicated algorithms and systems, they are a great structuring force. Which is part of why I love D: auto and Variant lets you forget about a lot of it, but you can still be explicit when it is important. My two cents, NMS
Re: Chaining a dynamic number of Ranges
On Saturday, 21 July 2012 at 16:42:50 UTC, Enerqi wrote: Hello I'm playing around with my first D program and can't figure out a way to chain a dynamic number of ranges. In this example I'm trying to chain a two dimensional array into effectively a one dimensional array, so I can later sort it as one sequence. import std.algorithm; import std.range; // n is determined at runtime uint[][] arrays = new uint[][n]; foreach(ref a; arrays) { a = new uint[10]; copy(iota(10), a); } auto c = chain(arrays[0], arrays[1]); foreach(a; arr[2..$]) { c = chain(c, a); } Gives a compile error: Error: cannot implicitly convert expression (chain(c,a)) of type Result to Result any ideas? Thanks. The problem is that the first auto c is a chaining of an array and array, and chain(c, a) is a chaining of a chain of arrays and an array. The way to do this is std.algorithm.joiner: auto c = joiner(arrays, []); Forgive me if I'm wrong (untested), NMS
Re: reference to 'self' inside a function
On Tuesday, 17 July 2012 at 16:56:17 UTC, angel wrote: I propose to introduce a reference to the current function, much like 'this' in a class method. Call it 'self' or 'thisFunc', or whatever ... What might this be good for ? For implementing recursion in a lambda function. Writing in functional style, one creates many functions, and looking for reasonable names for these functions becomes unnecessarily painful. May I suggest the recur or recursive keyword? auto factorials = map!(n = n ? n * recur(n-1) : 1)([1, 2, 3]).array; assert(factorials == [1, 2, 6]); NMS
Re: Concurrency in D
On Wednesday, 27 June 2012 at 22:34:51 UTC, Minas Mina wrote: I have been playing latetly with std.concurrency and core.thread. I like both, but they are entirely different approaches to concurrency. Aren't they great? ;) std.concurrency: Uses message passing. Does not allow passing of mutable types. core.thread: Essentially the same as the approach taken by Java. 1) Is one favoured over the other? I guess std.concurrency would be, because it uses messages (and I recently read somewhere that immutability + message passing = good thing). Personally I favor std.concurrency, in many cases I find it faster. Well, my problem about is, how can send mutable data to another thread? _Can_ I do it? If not, how am I supposed to share data between them? Not everything can be immutable right? Mutable value types can be sent easily, because they are copied. You share data with shared(T) types, e.g. shared(Object) or shared(int[]). However, I try to avoid shared data by keeping it in single threads, and having other threads access parts with message passing. One paradigm is to isolate data into thread objects, threads which have non-shared data on the stack, and have other threads send GetData messages and get ReturnedData messages. For example I would like to have a thread calculate the sum of the first half of an array while another thread would calculate the other half, and I could add the two results at the end. Check out this: http://dpaste.dzfl.pl/0f7ccb79 Note that for algorithms like this, you should check out std.parallelism, it's more high-level than std.concurrency. 2) What about core.thread? To do proper sync between threads in core.thread, semaphore, mutexes and stuff like that are needed. Are those good practice in D? Part of D's philosophy is you can get low-level and dirty if you want, but the easy/safe way should also be the fast way. core.thread is there for you, but std.concurrency is easier. Note that std.concurrency is written on top of core.thread. I definitely prefer std.concurrency, but I don't write CPU-intensive stuff anyway, so I'm no expert. 3) I have also read a bit about syncronized classes and shared classes/structs, altough I didn't understand it too much (well I didn't try too much to be honest). Objects of a synchronized class automatically lock/unlock every method call. You don't share stack structs, though maybe shared(StructType)*. For all those appoaches, which is the preffered? For all those appoaches, which is the preffered for game programming? Thank you. Hope I've helped. NMS
Re: Template Interface
On Wednesday, 13 June 2012 at 13:34:25 UTC, Nick Treleaven wrote: On 12/06/2012 18:56, Nathan M. Swan wrote: When writing a generic function which takes an unknown type, the signature is written like so: void fun(L)(L l) if (isList!L); While writing a generic interface is written like so: template isList(L) { enum bool isList = is(typeof( (inout int _dummy=0) The above line seems unnecessary as we have {no_argument_lambda;} syntax - or is there a special reason why? I'm not sure, I just found it throughout std.range { L l; if (l.nil) {} auto e = l.car; l = l.cdr; )); } BTW I think Walter said we could have enum template syntax, which would improve the above a little: enum bool isList(L) = is(typeof(... This doesn't seem very intuitive to me. OOP languages handle this with interfaces, but in D for things like ranges we often use structs, making it incompatible with the current interface. A possible enhancement is to allow structs to implement interfaces (but this has a runtime cost, unlike using templates). I'm suggesting something like a template interface, which is compatible with all types, and serves as a placeholder for any type for which the body compiles: [snip] void fun(List!string l); Maybe: void fun(L:IList)(L l); template interface IList(E) { template interface List(E) : List { List!E l; E e = l.car; } It makes writing generic code much cleaner. I'm not quite sure what the ': List' part means - is it just to declare that the List struct is used below? That List!E inherits from list. I'm not sure this is necessary or not. Maybe it would be better for the template interface body to contain method signatures/members rather than code? I considered that, but somethings aren't just methods. A range's empty could be enum empty = false, bool empty, or @property bool empty. The whole point of the range interface is syntactic similarity, though the semantics might be different. I think it might be an interesting idea, but it would probably need to be significantly better than the current way with constraints to get adopted by D. Nick Yea, this isn't a specific proposal, just an idea put out there. NMS
Template Interface
When writing a generic function which takes an unknown type, the signature is written like so: void fun(L)(L l) if (isList!L); While writing a generic interface is written like so: template isList(L) { enum bool isList = is(typeof( (inout int _dummy=0) { L l; if (l.nil) {} auto e = l.car; l = l.cdr; )); } This doesn't seem very intuitive to me. OOP languages handle this with interfaces, but in D for things like ranges we often use structs, making it incompatible with the current interface. I'm suggesting something like a template interface, which is compatible with all types, and serves as a placeholder for any type for which the body compiles: void fun(List l); template interface List { List l; if (l.nil) {} auto e = l.car; l = l.cdr; } It might be have parameters: void fun(List!string l); template interface List(E) : List { List!E l; E e = l.car; } It makes writing generic code much cleaner. Thoughts? NMS
Re: Code-File structure
On Tuesday, 12 June 2012 at 07:04:15 UTC, Henrik Valter Vogelius Hansson wrote: Hi! I'm new to D and trying everything out. Got the basics down which are very straightforward and similar to other languages. My professional background is primarily in C/C++-variants and Ruby if it helps. I have a problem with how modules, packages and files work. I don't really know how I am supposed to organize my code. I like namespaces from C++ which is probably my curse. What I want to write is code similar to this: MyClass obj = new MyClass(); SomePackage.SecondClass secondObj = new SomePackage.SecondClass(); Problem here is that SecondClass is a module. Is there some nifty trick I can do here to solve this? I tried with just having one module file which would hold all it's classes and functions but that backfired very quickly as you can imagine since it grew too large too quickly for most simple things. I am open to any suggestions of course which would make it simple for me to have a good structure with my files and also make my code easily readable. Though if possible I would like anything that goes under the package/module can somehow be placed in it's own folder. A module is a file, which can contain multiple functions/classes/etc. A package is a folder with files. You cannot put multiple modules in a file like C++ namespaces. Generally, I create multiple modules in a single package, and only use multiple packages when I have too many modules. Here's a sample file structure: src - ddi - color.d - csv.d - io.d - main.d - msg.d A larger project, SDC, has 15 modules in the main package, and six subpackages with on average five modules inside them. I like the rule-of-15 in whether something is too big, though that is personal taste and you might like more structure than I do. In this case, have SomePackage be some_module, and have SecondClass be inside of some_module.d: auto obj = new MyClass(); auto secondObj = new some_module.SecondClass(); It's convention to _always_ use lower case, due to different filesystem's rules on case. Hope this helps, NMS
Re: Array Concatenate
On Friday, 8 June 2012 at 12:41:13 UTC, Paul wrote: If this works... D programming book section 4.1.9 Expanding auto a = [87, 40, 10]; a ~= 42; assert(a== [87, 40, 10, 42]); why doesnt' this work? DeletedBlks ~= matchOld[0]; the dmd compiler comes back with Error: cannot append type string to type string[ulong] Does this append operator only work for literals? It seems like you're confusing _associative_ arrays with _regular_ arrays; they are different things. A regular array is written as T[], or an array of Ts. An associative array is written as K[V], or a map from K to V. If you have a list of something, use string[], not string[ulong].
Re: mutable reference pointer
On Wednesday, 6 June 2012 at 11:45:34 UTC, Gor Gyolchanyan wrote: I had this idea for a long time now and was trying to find a reason why it was a bad idea. I failed to find that reason, so here it is: The idea is to have a mutable reference: int a; // This is a mutable reference (essentially a pointer, but with reversed behavior). assert(a is null); // the address must be taken before address-related operations can be performed a = 20; // Access violation error due to null pointer dereferencing. a = new int; // Addresses, taken from mutable references are lvalues. a = 20; assert(a == 20); c = null; assert(c is null); The idea here is to further reduce the need to explicitly deal with addresses, while providing the number one reason why people use pointers: indirection. This mechanism will exclude indirection from the list of reasons why one would use pointers. This is also good for reducing compiler magic, when dealing with ref parameters and return types for functions. This mutable reference would be the complete compliment of pointers: dereferencing a pointer yields a mutable reference, taking address of a mutable reference yields a mutable pointer. This is not a proposition to add to D, but rather an idea, which could eventually end up in D if you guys think it's worth it. It could also be used to remove the magic from reference types, by adding their non-reference counter-parts and have their constructors return such a mutable reference. Here's a consideration: when I was a beginner learning C++ the difference between reference and pointer types (and their operators) confused me so much I avoided learning what pointers were for a long time: type create from t T* ptr = t T ref = t
Re: More synchronized ideas
On Tuesday, 5 June 2012 at 05:14:36 UTC, Nathan M. Swan wrote: On Monday, 4 June 2012 at 11:17:45 UTC, Michel Fortin wrote: After trying to make sense of the thread synchronized (this[.classinfo]) in druntime and phobos, I had to write my opinion on all this somewhere that wouldn't be instantly lost in a bazilion of posts. It turned out into something quite elaborate. http://michelf.com/weblog/2012/mutex-synchonization-in-d/ This encourages the bad practice (IMO) of shared data. Only a single thread should have the dictionary, with an AddWordMsg struct and a ConfirmWordMsg struct. Using a message passing approach, the client thread sends an AddWordMsg and continues while the word is added concurrently, making it more efficient. My non-expert opinion, NMS Though on the flip side, part of the D ideology is not restricting the programmer to a single paradigm. So maybe I like the idea :) Data sharing should still be discouraged. NMS
Re: More synchronized ideas
On Monday, 4 June 2012 at 11:17:45 UTC, Michel Fortin wrote: After trying to make sense of the thread synchronized (this[.classinfo]) in druntime and phobos, I had to write my opinion on all this somewhere that wouldn't be instantly lost in a bazilion of posts. It turned out into something quite elaborate. http://michelf.com/weblog/2012/mutex-synchonization-in-d/ This encourages the bad practice (IMO) of shared data. Only a single thread should have the dictionary, with an AddWordMsg struct and a ConfirmWordMsg struct. Using a message passing approach, the client thread sends an AddWordMsg and continues while the word is added concurrently, making it more efficient. My non-expert opinion, NMS
Re: synchronized (this[.classinfo]) in druntime and phobos
On Monday, 28 May 2012 at 23:55:04 UTC, Alex Rønne Petersen wrote: On 29-05-2012 01:46, Jonathan M Davis wrote: On Tuesday, May 29, 2012 01:38:25 Alex Rønne Petersen wrote: I should probably add that Java learned it long ago, and yet we adopted it anyway... blergh. The lesson learned from Java that TDPL enumerates is the mistake of having synchronized on functions rather than entire classes, but clearly even that is currently TDPL-only and not actually properly implemented yet. - Jonathan M Davis But synchronized on entire classes is exactly equally flawed... the fundamental problem is still that they synchronize on a public resource. The fundamental problem is shared memory ;) NMS
Re: Simplified socket creation and handling
On Monday, 21 May 2012 at 17:54:56 UTC, Adam D. Ruppe wrote: On Saturday, 19 May 2012 at 20:33:49 UTC, Nathan M. Swan wrote: It has some pitfalls (e.g. I can't find a good way to stop the server) When I use it, I just leave it open in a terminal window. Control+C can then kill it. (I'm on linux but I think the same would apply on Windows.) That's the only way right now. I was trying to make break; work in that connect opApply thing, but it didn't work right so there is no quit ability inside the app right now. That's what I've done too, though it fails to call destructors. I tried manager.quit(), but it results in segfaults for some reason (I think it has something to do with background threads).
Re: std.concurrency.send
On Sunday, 20 May 2012 at 04:09:50 UTC, japplegame wrote: public: void startLogger(LogConstructorArgs args) { loggerTid = spawn(loggerThread, args); } void log(string msg, OtherOptions oo) { loggerTid.send(LogMsg(msg, oo)); } void stopLogger() { loggerTid.send(QuitMsg()); } private: Tid loggerTid; struct LogMsg { string msg; OtherOptions oo; } struct QuitMsg {} void loggerThread(LogConstructorArgs args) { Logger lg = new Logger(args); bool cont = true; while(cont) { receive((LogMsg lm) { lg.log(lm.msg, lm.oo); }, (QuitMsg qm) { cont = false; }); } } I don't understand. In this way I should call startLogger/stopLogger in every application thread because loggerTid is thread related and every application thread has its own instanse of loggerTid. Instead N+1 threads (N application and 1 logger) we will get 2*N threads (N application and N loggers). Also we should synchronize Logger class because many instances of them will run concurrently. This is terrible. Tids aren't threads, they're thread-IDs, so you wouldn't be creating threads. Though you're right in that tids would need to be shared (for some reason I assumed that child thread TLS storage was copied from its parents). In general, this shows an important principle of D-ish concurrent programming: avoid globals. In your situation, here's what I'd do: struct Logger { void start() { loggerTid = spawn(loggerThread, args); } void stop() { loggerTid.send(QuitMsg()); } void log(string msg) { loggerTid.send(LogMsg(msg)); } Tid loggerTid; } Construct loggerThread like the class-to-thread I show below, so you don't need a Logger class, and make sure to start() at the beginning and stop() at the end, and pass your Logger struct around. This may seem like an inconvenience compared to a shared synchronized object, but here's an interesting thought: once a working thread sends a message to the logger thread to log, it can continue with its work. This makes it more efficient than having to wait for the logging to finish before continuing with work, which is what you'd do with synchronized(this). You are only doing synchronized(queue) in the background. What D is doing is making it easier to do it the right/efficient way (message passing), by making the usually simple way (shared objects) inconvenient. Note: unfortunately, I'm not sure if the Logger will work due to this bug: http://d.puremagic.com/issues/show_bug.cgi?id=4957 Hopefully it's fixed soon :( If you are passing objects between threads, make it shared. This might seem annoying, but in general you should try to shift your thinking into having thread-local objects and communicating via structs. But when you use global/singleton objects (any case where there's one instance of the class), convert it into a thread, FROM class name { this(cons args) { constructor } void method1() { // ... } int method2() { int result; // ... return result; } private fields // you encapsulate and have no public fields, right? } TO void nameThread(cons args) { private fields constructor bool cont = true; while(cont) { receive( (method1Msg) { // ... }, (Tid r, method2Msg) { int result; // ... r.send(method2ReturnMsg(result)); } (QuitMsg qm) {cont = false;}); } } Intresting idea. I will try it. Thanks. I like to thing of this idea as the thread-object paradigm. I've considered using D's great templating ability to allow you to make a class and have it be converted to a thread-object, but the __traits(getMember) stuff is confusing. NMS
Re: std.concurrency.send
On Saturday, 19 May 2012 at 13:26:20 UTC, japplegame wrote: Multithreading in D confuses me more and more. import std.concurrency; import std.stdio; shared Tid tid; void main() { send(cast(Tid)tid, Hello, World); } void worker() { writeln(receiveOnly!string); } shared static this() { tid = cast(shared)spawn(worker); } I hate these explicit casts. It is impossible sharing anything between threads without these ugly casts from/to shared. Seems like something wrong in program design when I'm forced to use explicit casts. But I don't understand what is it exactly. You don't need to mark Tids as shared. For example. I need create mutable object in one thread and send to another. I don't need to share this object, just create, send and forget. But I have no idea how make this without using shared attribute and casting to/from it. If you originally create it as shared, you don't need to do the casting.
Re: Simplified socket creation and handling
On Friday, 18 May 2012 at 06:35:59 UTC, Jarl André wrote: I am a Java developer who is tired of java.nio and similar complex socket libraries. In Java you got QuickServer, the ultimate protocol creation centered socket library. You don't have to write any channels and readers and what not. You just instantiate a server, configures the handlers (fill in classes that extends a handler interface) and there you go. Shouldn't there exist a similar library in any programming language? Not doing so is assuming that developers always need control of the lower layers. Its not true. I care about protocol. Not sockets. Is there any abstraction layers in phobos? Or is everything just as complex as before? Check out arsd: https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff I used cgi.d to make my own server easily (compile with -version=embedded_httpd). If you want more lower-level control, try a ListeningConnectionManager. To see how it's used, look at the code starting on line #1926. It has some pitfalls (e.g. I can't find a good way to stop the server), but it is very nice in _easily_ starting up, with _zero_ config. NMS
Re: std.concurrency.send
On Saturday, 19 May 2012 at 21:13:14 UTC, japplegame wrote: You don't need to mark Tids as shared. Okay. I'm writting logger. Logger is global object and it is running in its own separate thread (for example, writting logs to remote database). My application has several threads and all of them want to log something. How to share this global logger between threads? I think the simplest way is to share logger's thread tid and other thread can send logs via this shared tid. public: void startLogger(LogConstructorArgs args) { loggerTid = spawn(loggerThread, args); } void log(string msg, OtherOptions oo) { loggerTid.send(LogMsg(msg, oo)); } void stopLogger() { loggerTid.send(QuitMsg()); } private: Tid loggerTid; struct LogMsg { string msg; OtherOptions oo; } struct QuitMsg {} void loggerThread(LogConstructorArgs args) { Logger lg = new Logger(args); bool cont = true; while(cont) { receive((LogMsg lm) { lg.log(lm.msg, lm.oo); }, (QuitMsg qm) { cont = false; }); } } If you originally create it as shared, you don't need to do the casting. Yes. I don't need to cast to shared, but inside thread I get shared object and can't store/call/pass it without casting away that shared attribute. Or I should make shared everyting that have deal with shared object. I'am trying to follow Safe D concept, but it forbids casting away shared. If you are passing objects between threads, make it shared. This might seem annoying, but in general you should try to shift your thinking into having thread-local objects and communicating via structs. But when you use global/singleton objects (any case where there's one instance of the class), convert it into a thread, FROM class name { this(cons args) { constructor } void method1() { // ... } int method2() { int result; // ... return result; } private fields // you encapsulate and have no public fields, right? } TO void nameThread(cons args) { private fields constructor bool cont = true; while(cont) { receive( (method1Msg) { // ... }, (Tid r, method2Msg) { int result; // ... r.send(method2ReturnMsg(result)); } (QuitMsg qm) {cont = false;}); } }
Re: deprecating std.stream, std.cstream, std.socketstream
On Monday, 14 May 2012 at 15:02:11 UTC, Steven Schveighoffer wrote: In other words, a stream of bytes, not a good range (who wants to get one byte at a time?). A stream of UTF text broken into lines, a very good range. There are several cases where one would want one byte at the time; e.g. as an input to another range that produces the utf text as an output. I do agree for e.g. with binary data some data can't be read with ranges (when you need to read small chunks of varying size), but that doesn't mean most things shouldn't be ranged-based. NMS
Re: deprecating std.stream, std.cstream, std.socketstream
On Sunday, 13 May 2012 at 21:39:07 UTC, Walter Bright wrote: 4. they should present a range interface, not a streaming one I was just about to make a post suggesting that! You could easily integrate std.io with std.algorithm to do some pretty cool things. NMS
Re: What library functionality would you most like to see in D?
On Thursday, 10 May 2012 at 19:11:48 UTC, sclytrack wrote: I want to see the following library feature the most. apt-get install d-library-name Or even better: a D packaging system
Re: Notice/Warning on narrowStrings .length
On Friday, 27 April 2012 at 06:12:01 UTC, H. S. Teoh wrote: On Thu, Apr 26, 2012 at 09:55:54PM -0400, Nick Sabalausky wrote: [...] Crazy stuff! Some of them look rather similar to Arabic or Korean's Hangul (sp?), at least to my untrained eye. And then others are just *really* interesting-looking, like: http://www.omniglot.com/writing/12480.htm http://www.omniglot.com/writing/ayeri.htm http://www.omniglot.com/writing/oxidilogi.htm You're right though, if I were in charge of Unicode and tasked with handling some of those, I think I'd just say Screw it. Unicode is now depricated. Use ASCII instead. Doesn't have the characters for your langauge? Tough! Fix your language! :) You think that's crazy, huh? Check this out: http://www.omniglot.com/writing/sumerian.htm Now take a deep breath... ... this writing was *actually used* in ancient times. Yeah. Which means it probably has a Unicode block assigned to it, right now. :-) It was actually the first human writing ever. Which Phoenician scribe knew that his innovation of the alphabet would make programming easier thousands of years later?
Re: What to do about default function arguments
On Thursday, 26 April 2012 at 03:44:27 UTC, Walter Bright wrote: A subtle but nasty problem - are default arguments part of the type, or part of the declaration? See http://d.puremagic.com/issues/show_bug.cgi?id=3866 Currently, they are both, which leads to the nasty behavior in the bug report. The problem centers around name mangling. If two types mangle the same, then they are the same type. But default arguments are not part of the mangled string. Hence the schizophrenic behavior. But if we make default arguments solely a part of the function declaration, then function pointers (and delegates) cannot have default arguments. (And maybe this isn't a bad thing?) I don't think it's a bad thing: default arguments in the type system mean values in the type system. NMS
[Kinda OT] httpd permissions
How do I deal with this (on OSX); are CGI programs not allowed to write to files? How to change this? Thanks, NMS test.d: #!/usr/local/bin/rdmd import std.stdio; void main() { writeln(Content-type: text/plain\r\n\r\nHello, World!); } error log: [Wed Apr 25 00:03:01 2012] [error] [client ::1] sh: /Users/nathanmswan/Sites/test.d.deps: Permission denied [Wed Apr 25 00:03:01 2012] [error] [client ::1] Failed: dmd -v -o- '/Users/nathanmswan/Sites/test.d' -I'/Users/nathanmswan/Sites' /Users/nathanmswan/Sites/test.d.deps [Wed Apr 25 00:03:01 2012] [error] [client ::1] Premature end of script headers: test.d
Re: [Kinda OT] httpd permissions
Have you checked that your web server has write access to /Users/nathanmswan/Sites/ ? Yes, it works now, thanks! NMS P.S. Sorry this might be in the wrong forum, but now I can advertise my homepage as index.d instead of compiling it and having it be index.cgi
Re: Pointer to variables in D
On Thursday, 26 April 2012 at 02:43:35 UTC, Victor Vicente de Carvalho wrote: Hi there, In c++ one can access a pointer to a class/struct variable using this semantic: struct C { int x; }; int C::* ptr = C::x; C foo; foo.*ptr = 10; assert(foo.x == 10); It is possible to do something like that on D? I've searched through the forum documentation but didn't found anything. This is the closest thing: --- struct C { int x; int* ptr() @property { return x; } } C foo; *foo.ptr = 10; assert(foo.x = 10); --- Also, the reason of this is that I'm studying a way to map a POD structure based from a dynamic, data-driven structure. Something like get a JSON and map it to a structure automagically. There is a nicer way to do that in D? Yes. My rule: don't use pointers unless doing it otherwise is really slow or really hard.
Re: XSort - Sorting algorithms (including Timsort!)
On Thursday, 12 April 2012 at 03:04:49 UTC, Xinok wrote: I just wanted to share this. I started a project a few weeks ago on Github to implement several sorting algorithms in D. In total, there are 8 modules at the moment, each implementing a sorting algorithm or combination thereof. https://github.com/Xinok/XSort I just finished Timsort today. It's working, it's stable, but I need to spend a little more time better optimizing it. Cool! To make it a bit more generic, may I suggest making all the inputs only have to be isInputRange, and have it converted to an array. NMS
Re: An idea to improve eponymous templates
On Thursday, 12 April 2012 at 02:21:46 UTC, Reid Levenick wrote: Firstly, I had no idea where suggestions should go, and I saw a few others here and thus here I am. I was writing some code that depended heavily on my own eponymous templates, and decided to change the names of some of them to make them more self-documenting. However, after changing the name, I encountered a long stream of unintelligible errors (to me, I haven't been using D for a long time) about template instances. So, my idea is that the 'this' keyword could be used in templates as a shortcut for eponymous templates, allowing code like this template anEponymousTemplate( size_t whatever ) { enum this = whatever * 2; } template anotherOne( T ) { static if( is( T == class ) ) { alias long this; } else { alias int this; } } Which would reduce cruft and make it easier to read some templates, as well as reducing maintenance. I like the idea. To get rid of any confusion with keywords, name-mangling, or classes, I suggest having this being syntactic sugar for the name of the template. NMS
Encodings
For most of the string processing I do, I read/write text in UTF-8 and convert it to UTF-32 for processing (with std.utf), so I don't have to worry about encoding. Is this a good or bad paradigm? Is there a better way to do this? What method do all of you use? Just curious, NMS
deimos libX11 not compiling
I'm not sure if I would post this here, but: https://github.com/D-Programming-Deimos/libX11/issues/7
Re: UFCS for D
On Thursday, 29 March 2012 at 00:21:38 UTC, Andrei Alexandrescu wrote: http://www.reddit.com/r/programming/comments/rif9x/uniform_function_call_syntax_for_the_d/ Andrei The primitives/utility distinction is an idea I've thought about a lot. UFCS is justifiable not only as a syntactic convenience but as a solution to an important design principle. Great work guys! NMS
structs, tids, and concurrency.
Nesting a Tid in a struct is interpreted as having local aliasing, though a bare Tid is not. This doesn't work, though commenting out receiveOnly!S() and tid.send(S(thisTid)) works: - import std.stdio; import std.concurrency; void main() { auto thread = spawn(function void(Tid tid) { tid.send(thisTid); tid.send(S(thisTid)); }, thisTid); receiveOnly!Tid(); receiveOnly!S(); } struct S { Tid tid; } - $ rdmd test.d /usr/share/dmd/src/phobos/std/concurrency.d(319): Error: static assert Aliases to mutable thread-local data not allowed. ../test.d(9):instantiated from here: send!(S) Failed: dmd -v -o- '../test.d' -I'..' ../test.d.deps
Re: Documentation Layout
On Wednesday, 28 March 2012 at 14:47:53 UTC, Adam D. Ruppe wrote: On Wednesday, 28 March 2012 at 06:20:57 UTC, James Miller wrote: 1. The Jump To index. I did a little program called improveddoc that builds nicer tables: http://arsdnet.net/d-web-site/improveddoc.d makes: http://arsdnet.net/d-web-site/std_stdio.html It does post-processing on the dom to build it. That's pretty cool! I especially like the categories idea; it reminds me of Apple's documentation for Cocoa. It really helps you when you are thinking I need a function which does NMS
Re: Documentation Layout
On Wednesday, 28 March 2012 at 22:43:19 UTC, foobar wrote: Categories - worst idea ever. What's better: int a; // this is size OR int size; Same thing applies here - code MUST be self documenting as much as possible. But categories are still useful, e.g., when you want a function in std.algorithm that looks for a specific element. It could be search or find or firstElemSatisfyingCondition, and even though those are all self documenting, it would be a pain to look through the list of functions in alphabetical order. The use of categories narrows your search for the function down 20%. NMS
Re: Issue 3789, stucts equality
On Monday, 26 March 2012 at 21:25:06 UTC, Alvaro wrote: Maybe it makes more sense that struct==struct applies == to each of its fields. It would be the same as bitwise comparison for simple primitive types, but would be more useful with other types such as strings. +1
Re: dcaflib
On Monday, 26 March 2012 at 13:56:46 UTC, Dejan Lekic wrote: Nathan, what terminals are supported? Only ANSI / VT* or some other types of terminals as well? I've only tested it on OSX Terminal, but I read about the features on a Linux website, and have used the ANSI escape code Wikipedia article as reference, so I assume it's ANSI. NMS
Re: Proposal for a MessageQueue (was Re: public MessageBox)
On Friday, 23 March 2012 at 12:36:42 UTC, David Nadlinger wrote: Are you trying to build std.concurrency from Git master against Phobos 2.058 or something like that? David I cloned from git://github.com/D-Programming-Language/phobos.git NMS
Re: Proposal for a MessageQueue (was Re: public MessageBox)
On Thursday, 22 March 2012 at 15:53:56 UTC, Sean Kelly wrote: I can see adapting the API so that each thread has a default message queue (keep in mind that we'll be adding interprocess messaging at some point via the same routines). I'm not yet clear how the existence of alternate message queues could be communicated to other portions of the code though. register() is one way I suppose. Really what's happening here is that Tid is being replaced by a queue ID, not extended with a mutable variable. I think they would be passed as parameters to spawn or received from the default message queue. I guess Tid would become an alias for the Qid created when a thread is spawned. What I really don't want though, is for receive() to operate on a message queue created in a different thread. Messaging would become substantially slower if receive() had to be synchronized. That's a drawback I haven't considered. To solve this, it would be made part of the contract that receiving must all be done in one thread. I can't think of a use where receiving in multiple threads would apply, but if it would, a SynchronizedMessageQueue subclass could easily be drawn up that broadens the contract and synchronizes for receive(). BTW, how do you unittest just the std.concurrency module?
Re: Proposal for a MessageQueue (was Re: public MessageBox)
On Thursday, 22 March 2012 at 21:27:40 UTC, Sean Kelly wrote: On Mar 22, 2012, at 12:06 PM, Nathan M. Swan nathanms...@gmail.com wrote: On Thursday, 22 March 2012 at 15:53:56 UTC, Sean Kelly wrote: I can see adapting the API so that each thread has a default message queue (keep in mind that we'll be adding interprocess messaging at some point via the same routines). I'm not yet clear how the existence of alternate message queues could be communicated to other portions of the code though. register() is one way I suppose. Really what's happening here is that Tid is being replaced by a queue ID, not extended with a mutable variable. I think they would be passed as parameters to spawn or received from the default message queue. But will either of those solve the problem you outlined where user code is calling receiveOnly and bumping into a message meant for a third-party API? If the API is spawning threads they typically won't be running user code, or at least would certainly impose restrictions on message queue use by called user code. And in the case of sending the Qid to the default queue, you end up with a race condition where user code might call receiveOnly. But what if the client spawns threads? An example would be with a desktop GUI. In a background thread meant for a CPU-intensive task, they want to update a progress indicator and send partially-calculated data to a main-thread. void mainThread() { string data; auto mq = new MessageQueue(); spawn(backgroundThread, mq, pi); pi.onChange = (double val) { if (val == 0.5) { data = me.receiveOnly!string(); } else { data ~= me.receiveOnly!string(); } }; } void backgroundThread(MessageQueue me, ProgressIndicator pi) { // part 1 of calculations... me.send(partiallyCalculatedData); pi.value = 0.5; // implementation: this._queue.send(UpdateValue(value)) // part 2... me.send(theRestOfTheData); pi.value = 1.0; } With one MessageQueue per thread, the mailbox would contain a (string, UpdateValue, string, UpdateValue). The mainThread would expect a (UpdateValue, string, UpdateValue, string). This way, the client code is separated from the library. The default queue is an idea suggested for backward compatibility, and new programmers wouldn't be encouraged to use it. I guess Tid would become an alias for the Qid created when a thread is spawned. What I really don't want though, is for receive() to operate on a message queue created in a different thread. Messaging would become substantially slower if receive() had to be synchronized. That's a drawback I haven't considered. To solve this, it would be made part of the contract that receiving must all be done in one thread. I can't think of a use where receiving in multiple threads would apply, but if it would, a SynchronizedMessageQueue subclass could easily be drawn up that broadens the contract and synchronizes for receive(). BTW, how do you unittest just the std.concurrency module? Not easily, since a failure often means that a thread hangs. Linking fails (I'm on OSX): $ rdmd --main -unittest std/concurrency.d Undefined symbols for architecture x86_64: _D3std3utf10strideImplFNaNeamZk, referenced from: _D3std3utf15__T6strideTAxaZ6strideFNaNfxAamZk in concurrency.d.o _D3std3utf14__T6strideTAaZ6strideFNaNfxAamZk in concurrency.d.o _D3std3utf15__T6strideTAyaZ6strideFNaNfxAyamZk in concurrency.d.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status --- errorlevel 1 Thanks, NMS
Re: Proposal for a MessageQueue (was Re: public MessageBox)
On Friday, 23 March 2012 at 00:14:00 UTC, Sean Kelly wrote: While sending messages like a bare string might be good for example code, any real application is going to use structured messages whose type is specific to what the message is for, contains fields like sender Tid, etc. It seems like you're aiming more for CSP where you'd create a separate communication channel per use. You could even fake it by wrapping send/receive with your own CSP-like API, though it's quite likely that a from-scratch CSP style implementation would be faster because there'd be no need to package messages. I see your point. To make this easier, may I suggest: T receiveNext(T)() { T r; receive((T t) {r = t;}); return r; } A big reason for the use of receiveOnly (in my code) is its convenience. receiveNext, and a discouragement of using receiveOnly, would be a simpler solution. Used to work, and std.concurrency doesn't even use std.utf. Not sure what's going on there. Weird :( NMS
Re: public MessageBox
On Wednesday, 21 March 2012 at 19:53:55 UTC, Sean Kelly wrote: On Mar 20, 2012, at 8:37 PM, Nathan M. Swan wrote: After playing around with making a library with uses threads, I realized it would be nice if there could be multiple inter-thread mailboxes than just one per thread. That way, client code and third-party library code don't interfere with each other. They shouldn't interfere anyway. The third-party code just has to devise a message format that client code won't look for. Though if the client discards messages arbitrarily via receive((Variant v) {}) then all bets are off. What about this pseudocode? Thread1: spawn Thread2 library sends LibMsg client sends ClientMsg Thread2: client receives ClientMsg library receives LibMsg The client will receiveOnly!ClientMsg() and get a MessageMismatch. With multiple MessageBoxes: Thread1: clientmail = new MessageBox spawn Thread2(libobj, clientmail) libobj.mb.send(LibMsg) cleintmail.send(ClientMsg) Thread2: clientmail.receive(ClientMsg) libobj.mb.send(LibMsg) If you scroll down to the section commented out as doesn't work, it would work if my implementation could use MessageBoxes: https://github.com/carlor/dcaflib/blob/master/buggy/asyncobj.d As I posted a while back, the concept of a variant message queue is wonderful and powerful, and the implementation is great. But the fact that you can't declare auto mq = new MessageQueue() is a gaping whole in an otherwise A+ API. (A+ as the grade, not the array programming language ;) ) NMS
Proposal for a MessageQueue (was Re: public MessageBox)
On Wednesday, 21 March 2012 at 03:37:35 UTC, Nathan M. Swan wrote: After playing around with making a library with uses threads, I realized it would be nice if there could be multiple inter-thread mailboxes than just one per thread. That way, client code and third-party library code don't interfere with each other. So this is my proposal: that std.concurrency is modified so that class MessageBox is public and MessageBoxs be passed around through other MessageBoxs, or perhaps another class is devised for this. I'm not sure of the implications of this, though I know I would find it very useful by allowing me to write code without (import core.~someLowLevelModule) After thinking about this more, this is my proposal for the API. Backward compatibility is more important here than in other places because it is documented in TDPL. Each Tid contains a default MessageQueue accessible by property messageQueue. The send/receive functions and their variants operate on the tid's default messageQueue. The interface for class MessageQueue: void send(T...)(T vals); void prioritySend(T...)(T vals); void receive(T...)(T ops); receiveOnlyRet!(T) receiveOnly(T...)(T ops); bool receiveTimeout(T...)(Duration duration, T ops); @property void maxSize(size_t size); @property void onCrowding(OnCrowding oc); @property void onCrowding(bool function(MessageQueue) doThis); Hopefully, this won't break any current code, and it will be easy to implement.
public MessageBox
After playing around with making a library with uses threads, I realized it would be nice if there could be multiple inter-thread mailboxes than just one per thread. That way, client code and third-party library code don't interfere with each other. So this is my proposal: that std.concurrency is modified so that class MessageBox is public and MessageBoxs be passed around through other MessageBoxs, or perhaps another class is devised for this. I'm not sure of the implications of this, though I know I would find it very useful by allowing me to write code without (import core.~someLowLevelModule)
dcaflib
In a post from a few weeks ago, someone mentioned terminal colors. Currently, I have one that works with bash (cmd pending) at https://github.com/carlor/dcaflib. Example code: import dcaflib.ui.terminal; import std.stdio; void main() { fgColor = TermColor.RED; writeln(this is red!); fgColor = TermColor.BLUE; writeln(this is blue!); }
Re: comma inside is expression
On Thursday, 15 March 2012 at 02:34:45 UTC, Jos van Uden wrote: I've been reading the tutorial on templates and found this example: template rank(T) { static if (is(T t == U[], U)) // is T an array of U, for some type U? enum rank = 1 + rank!(U); // then let’s recurse down. else enum rank = 0; // Base case, ending the recursion. } TDPL never mentions the use of a comma operator inside an is expression. Is this an undocumented feature? Also the symbol 't' is never used, but if I remove it, it won't compile. It's a really good tutorial, but I find this particular example puzzling. Jos It's documented on the language reference: http://dlang.org/expression.html#IsExpression
Re: dereferencing null
On Friday, 2 March 2012 at 04:53:02 UTC, Jonathan M Davis wrote: It's defined. The operating system protects you. You get a segfault on *nix and an access violation on Windows. Walter's take on it is that there is no point in checking for what the operating system is already checking for - especially when it adds additional overhead. Plenty of folks disagree, but that's the way it is. - Jonathan M Davis One thing we must consider is that this violates scope safety. This scope(failure) doesn't execute: import std.stdio; void main() { Object o = null; scope(failure) writeln(error); o.opCmp(new Object()); } That's _very_ inconsistent with the scope(failure) guarantee of _always_ executing. NMS
Re: dereferencing null
On Tuesday, 6 March 2012 at 06:27:31 UTC, Jonathan M Davis wrote: scope(failure) is _not_ guaranteed to always execute on failure. It is _only_ guaranteed to run when an Exception is thrown. Any other Throwable - Errors included - skip all finally blocks, scope statements, and destructors. That's one of the reasons why it's so horrible to try and catch an Error. Maybe not guaranteed, but this happens: code: import std.stdio; void main() { scope(failure) writeln(bad things just happened); int[] x = new int[4_000_000_000_000_000_000]; } output: bad things just happened core.exception.OutOfMemoryError
Re: dereferencing null
On Saturday, 3 March 2012 at 02:51:41 UTC, Walter Bright wrote: Adding in software checks for null pointers will dramatically slow things down. What about the debug/release difference? Isn't the point of debug mode to allow checks such as assert, RangeError, etc? Segmentation fault: 11 prevents memory from corrupting, but it isn't helpful in locating a bug.
dereferencing null
Am I correct that trying to use an Object null results in undefined behavior? Object o = null; o.opCmp(new Object); // segmentation fault on my OSX machine This seems a bit non-D-ish to me, as other bugs like this throw Errors (e.g. RangeError). It would be nice if it would throw a NullPointerError or something like that, because I spent a long time trying to find a bug that crashed the program before writeln-debugging statements could be flushed. NMS
in not working with enum'd AA
I don't think this should happen: private enum KeywordsToTypes = [ importd: TT.KwIMPORT, publicd: TT.KwPUBLIC, protectedd : TT.KwPROTECTED, privated : TT.KwPRIVATE, staticd: TT.KwSTATIC, ]; static this() { // writes 0 std.stdio.writeln(importd in KeywordsToTypes); } Is there a reason why, or is this a bug?
Re: in not working with enum'd AA
On Monday, 27 February 2012 at 09:13:24 UTC, Jonathan M Davis wrote: It would be far better to use immutable. - Jonathan M Davis That doesn't work either, as it says: Error: non-constant expression [importd:cast(TokenType)2,publicd:cast(TokenType)3,protectedd:cast(TokenType)4,privated:cast(TokenType)5,staticd:cast(TokenType)6]
Re: The Right Approach to Exceptions
On Saturday, 18 February 2012 at 18:52:05 UTC, Andrei Alexandrescu wrote: There's a discussion that started in a pull request: https://github.com/alexrp/phobos/commit/4b87dcf39efeb4ddafe8fe99a0ef9a529c0dcaca Let's come up with a good doctrine for exception defining and handling in Phobos. From experience I humbly submit that catching by type is most of the time useless. Andrei Here's a compromise I would suggest: we have the different exception types for different exceptional behaviors, but still they all descend from a common exception type that has a field with the module name; this way, the client can choose which way they want to go. It would be nice if there was a mixin template that creates an exception class that acts like this; making similar exception classes is annoying.
Immutability, problems with debugging
I'm working on a novice solver of the travelling salesman problem, and when I decided to go concurrent I had to make everything immutable. Now this happens: /usr/share/dmd/src/phobos/std/format.d(1782): Error: function object.Object.toString () is not callable using argument types () immutable Unfortunately, I don't know how format is called, so I can't investigate closer. Does anyone notice anything glaringly obvious? https://github.com/carlor/tsp.d/blob/master/tsp.d This brings up an issue that's happened before; there's an error in the semantics of a (usually generic) function call, and I don't know where the function is called. It would be nice if the compiler could do something like mentioned on file1.d(33), mentioned on file2.d(107). Thanks, NMS
Immutability, problems with debugging
I'm working on a novice solver of the travelling salesman problem, and when I decided to go concurrent I had to make everything immutable. Now this happens: /usr/share/dmd/src/phobos/std/format.d(1782): Error: function object.Object.toString () is not callable using argument types () immutable Unfortunately, I don't know how format is called, so I can't investigate closer. Does anyone notice anything glaringly obvious? https://github.com/carlor/tsp.d/blob/master/tsp.d This brings up an issue that's happened before; there's an error in the semantics of a (usually generic) function call, and I don't know where the function is called. It would be nice if the compiler could do something like mentioned on file1.d(33), mentioned on file2.d(107). Thanks, NMS
Re: Immutability, problems with debugging
On Friday, 17 February 2012 at 10:49:19 UTC, Nathan M. Swan wrote: I'm working on a novice solver of the travelling salesman problem, and when I decided to go concurrent I had to make everything immutable. Now this happens: /usr/share/dmd/src/phobos/std/format.d(1782): Error: function object.Object.toString () is not callable using argument types () immutable Unfortunately, I don't know how format is called, so I can't investigate closer. Does anyone notice anything glaringly obvious? https://github.com/carlor/tsp.d/blob/master/tsp.d This brings up an issue that's happened before; there's an error in the semantics of a (usually generic) function call, and I don't know where the function is called. It would be nice if the compiler could do something like mentioned on file1.d(33), mentioned on file2.d(107). Thanks, NMS Sorry about the duplicate post, something weird went on with the forum interface.
The website structure
I want to create a fork of the website GitHub respiratory with a modified sidebar, but I don't see where I could do that. Thanks, NMS
Re: [RFC] Ini parser
On Thursday, 16 February 2012 at 20:50:23 UTC, Robik wrote: Feel free to share suggestions, changes, help me make it better :). It's great, I think I could find uses for it. One thing that confuses me about the implementation is that the IniSection has an array of key-value pairs. I think it would be more efficient, and cleaner code, to use an associative array.
Message-Passing
I want to applaud Sean Kelly and everyone who worked on std.concurrency for a great API, and wish that I could easily write Cocoa applications with it. I'm writing a screen recording program in Objective-C, and to make sure each frame has an equal length, I have two threads: one that takes the screenshot at certain intervals, the other that assembles it into a quicktime movie. After writing an implementation of a thread-safe queue, where the picture-taking thread adds and the assembling thread removes, I realized the huge similarity between what I'd done and std.concurrency. The std.concurrency module would have made hours of effort in ObjC take five minutes in D. Well done!