Re: Problem overloading operator for a struct with an immutable member
On Thursday, 26 March 2015 at 04:57:55 UTC, ketmar wrote: by the way. do you know that you still CAN overload postincrement operation? yes, the code is still here, and it works... somethimes. ;-) Thnaks. Indeed, this works: --- struct S { int i; immutable(Object) o; void opAddAssign(int j) { i += j; } S opPostInc() { ++i; return this; } void opAssign(S other) {} } unittest { S s; ++s; assert(s.i == 1); s++; assert(s.i == 2); } --- Old operator overloading to the rescue !
Problem overloading operator for a struct with an immutable member
I don't know if this is a bug or expected behaviour. The struct is mutable, assignable and pre-increment operator works. But post-increment doesn't compile because of the immutable member. -- struct S { int i; immutable(Object) o; S opUnary(string op)() { return this; } void opAssign(S other) {} } void main() { S s, t; t = s; // OK ++s; // OK s++; // Error: cannot modify struct s S with immutable members } ---
Re: A few notes on choosing between Go and D for a quick project
On Sunday, 15 March 2015 at 14:01:00 UTC, bearophile wrote: Walter Bright: I'd also prefer to get rid of /+ +/ comments, I thought they'd be more useful than they are. I prefer to get rid of /* */ instead :-) Because /++/ can do things /**/ can't. +1 And on my keyboard, /++/ is easier than /**/ :-)
Re: Testing implicit conversion to template instance with is() expression
On Sunday, 15 March 2015 at 18:33:32 UTC, Marc Schütz wrote: On Sunday, 15 March 2015 at 17:03:42 UTC, Marc Schütz wrote: https://issues.dlang.org/show_bug.cgi?id=14286 In the meantime, does someone know of a suitable workaround? I found the following workaround. Not beautiful, but it works: enum isValue(alias T) = __traits(compiles, typeof(T)); template isConvertibleToInstanceOf(alias From, alias To) if(isValue!From) { enum isConvertibleToInstanceOf = isConvertibleToInstanceOf!(typeof(From), To); } template isConvertibleToInstanceOf(From, alias To) if(!is(From == struct) !is(From == class) !is(From == interface)) { enum isConvertibleToInstanceOf = false; } template isConvertibleToInstanceOf(From, alias To) if(is(From == struct) || is(From == class) || is(From == interface)) { // workaround for https://issues.dlang.org/show_bug.cgi?id=14286 import std.typetuple : anySatisfy; enum aliasThisConvertible(string name) = isConvertibleToInstanceOf!(mixin(typeof(From. ~ name ~ )), To); enum isConvertibleToInstanceOf = anySatisfy!(aliasThisConvertible, __traits(getAliasThis, From)) || is(From : To!Args, Args...); } It works for your previous code example: static assert(isConvertibleToInstanceOf!(S!10, V)); // OK But this also works: static assert(!isConvertibleToInstanceOf!(S!10, V!abc)); // OK Can be reduced to: struct Foo(int i) {} alias Foo1 = Foo!1; static assert(is(Foo!2 == Foo1!T, T...)); // OK I think it's another bug.
Re: enum and static if
On Wednesday, 11 March 2015 at 17:19:20 UTC, ketmar wrote: On Wed, 11 Mar 2015 18:17:38 +0100, Artur Skawina via Digitalmars-d-learn wrote: On 03/11/15 15:41, ketmar via Digitalmars-d-learn wrote: On Wed, 11 Mar 2015 14:36:07 +, wobbles wrote: On Wednesday, 11 March 2015 at 14:34:32 UTC, ketmar wrote: On Wed, 11 Mar 2015 13:48:45 +, Namespace wrote: This code does not work: enum Test { Foo, static if (__VERSION__ = 2067) Bar, } Quatz } Any chance that this could work? nope. `static if` is statement, so it works only where statement is allowed. the same is true for `version`. this is by design. You can do something like static if (__VERSION__ = 2067) enum Test{ ... } else enum Test{ ... } as a workaround? sure, but you have to copypaste the whole enum in both places. maybe allowing `version` in enums worth a ER... mixin(` enum Test { Foo,` ~(__VERSION__=2067?` Bar,`:``) ~` Quatz }`); artur yes, it works. it also can be a participant in ugly D code of the month contest. ;-) The second prize in this contest could for: mixin(` enum Test { Foo, %s Quatz }` .format(__VERSION__ = 2067 ? Bar, : )); :)
Re: Int to float?
On Friday, 6 March 2015 at 00:57:16 UTC, Ola Fosheim Grøstad wrote: On Thursday, 5 March 2015 at 23:50:28 UTC, Jesse Phillips wrote: I think I read somewhere you don't want to use unions like this, but I think it is more because you generally don't want to reinterpret bits. It is non-portable, since some hardware architectures may use different representations (e.g. different byte order on int and float). Then maybe use std.bitmanip? import std.bitmanip; int i = 5; float f = bigEndianToNative!float(nativeToBigEndian(i)); // or float f = littleEndianToNative!float(nativeToLittleEndian(i));
Showcase your favorite language on Codegolf SE
In case nobody has noticed it yet, there's an interesting new challenge on codegolf.stackexchange called Showcase your language where you can only show a snippet of length equal to your number of upvotes (more detailed rule there). http://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time-experimental-challenge No D entry yet, but could be fun. -- Nicolas
Re: SQLLite driver
On Sunday, 14 December 2014 at 13:47:21 UTC, Suliman wrote: On Sunday, 14 December 2014 at 13:33:27 UTC, Suliman wrote: There is also a branch named `develop` which at least compiles, maybe it is usable. how to add to dub this branch? Compiling using dmd... Linking... OPTLINK (R) for Win32 Release 8.00.15 Copyright (C) Digital Mars 1989-2013 All rights reserved. http://www.digitalmars.com/ctg/optlink.html sqlite3.lib Warning 2: File Not Found sqlite3.lib C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_close C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_enable_shared_cache C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_open C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_changes C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_total_changes C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_errcode C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_errmsg C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_open_v2 C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_finalize C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_bind_parameter_count C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_clear_bindings C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_reset C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_step C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_prepare_v2 C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_count C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_type C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_name C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_text C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_double C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_int64 C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_blob C:\Users\Dima\AppData\Roaming\dub\packages\d2sqlite3-0.5.2\d2sqlite3.lib(d2sqlit e3) Error 42: Symbol Undefined _sqlite3_column_bytes --- errorlevel 22 FAIL .dub\build\application-debug-windows-x86-dmd_2066-668EB54A2EBB0CE5C55E2AC62 166BCB8\ seismodownloader executable Error executing command run: dmd failed with exit code 22. Warning 2: File Not Found sqlite3.lib Does it's mean that I should to find this lib and put it in package folder? Yes, you need to link the sqlite3 library, but I'm sorry I can't help you more, because I've never done this with dub on Windows... The develop branch is more up-to-date. It should compile with 2.066.1. And the API is supposed to be cleaner. See the examples to find the changes. -- Nicolas
Re: Delegates and C function pointers
On Saturday, 8 November 2014 at 16:01:09 UTC, anonymous wrote: On Saturday, 8 November 2014 at 12:23:45 UTC, Nicolas Sicard wrote: I would like to register a D delegate to a C API that takes a function pointer as a callback and a void* pointer to pass data to this callback. My solution is in http://dpaste.dzfl.pl/7d9b504b4b965. Is this code correct? Is there something simpler or already in Phobos that I have overlooked? Thanks -- Nicolas I think it's a little more complicated than it needs to be. Instead of going delegate-DelegateData*-delegate you can pass a pointer to the delegate: void doSomethingFromD(void delegate() dg) { static extern(C) void adapter(void* ptr) { auto dg = *cast(void delegate()*)ptr; dg(); } dosomething(adapter, dg); } dg is fine if dosomething calls the callback before doSomethingFromD returns. If the callback is stored and called later on, you have to put the delegate somewhere more lasting. And you have to make sure that the GC doesn't collect it in the meantime. In your code you're new-ing, but you don't keep the reference around in D-land. The GC would happily collect the delegate then, because it doesn't look in C-land for references. For example, you could add all callbacks to a module level array: void delegate()[] activeCallbacks; void doSomethingFromD(void delegate() dg) { static extern(C) void adapter(void* ptr) { auto dg = *cast(void delegate()*)ptr; dg(); } activeCallbacks ~= dg; dosomething(adapter, activeCallbacks[$ - 1]); } Then when everything's done and you know that the callbacks are not needed anymore, empty activeCallbacks so that the GC can collect them. Essentially, you're back to manual management, and have to think about the life times of the callbacks. Thanks for the advice about the GC managed references! I'll have a look at it. -- Nicolas
Re: module keyword with curly brackets
On Saturday, 1 November 2014 at 10:32:48 UTC, Jonathan M Davis via Digitalmars-d wrote: On Saturday, November 01, 2014 07:52:38 tcak via Digitalmars-d wrote: The module declaration, and the name and path of D files do not need to match each other. You include a D file while compiling the project, and module declarations are cared only. Based on above behaviour of design, allowing only one module keyword, and that is on top of D code file seems like a limitation to me (a little like just trying to copy Java, but leaving the work in the middle). Is there any VERY SPECIAL reason behind that limitation? How hard would it be to add a syntax as below? What problems could it create? test.d module a{ } module b{ module c{ } } In D, packages correspond to directories, and modules correspond to files. Yes, the module and package names can vary slightly from the file name, but that doesn't change the fact that they still correspond to specific files, and most folks don't give the modules names that don't match their file names. - Jonathan M Davis What's the reason why the module keyword was introduced in the first place? The package and module hierarchy could have been deduced from the directory and file hierarchy, as it is the case in Python, IIRC. The search rules just have to be clear. I know this has the side effect that module names can't be keywords or non-identifiers, but who would use such module names? -- Nicolas
Re: module keyword with curly brackets
On Saturday, 1 November 2014 at 14:40:16 UTC, Dicebot wrote: On Saturday, 1 November 2014 at 14:03:51 UTC, Nicolas Sicard wrote: What's the reason why the module keyword was introduced in the first place? The package and module hierarchy could have been deduced from the directory and file hierarchy, as it is the case in Python, IIRC. The search rules just have to be clear. I know this has the side effect that module names can't be keywords or non-identifiers, but who would use such module names? You can omit module declarations and those will be deduced indeed. However that will make package path dependent on compiler currend directory and this is why specifying qualified path explicitly is helpful. Compiling is already dependent on the current directory. And qualified path are not just helpful, they're required for packages, or did I miss something? I was thinking about the way Python does it: - 'dmd foo.d' = 'import foo;' (if foo.d is in cwd) - 'dmd mylib/internal/foo.d' = 'import mylib.internal.foo;' (if the path exists in the cwd) - 'dmd foo.d' and there is no foo.d in the cwd: use the search path from the config, or fail. I see no reason to put module declarations in single level projects with no packages. Yes, I don't put them!
Re: module keyword with curly brackets
On Saturday, 1 November 2014 at 15:32:22 UTC, Dicebot wrote: On Saturday, 1 November 2014 at 14:48:33 UTC, Nicolas Sicard wrote: On Saturday, 1 November 2014 at 14:40:16 UTC, Dicebot wrote: On Saturday, 1 November 2014 at 14:03:51 UTC, Nicolas Sicard wrote: What's the reason why the module keyword was introduced in the first place? The package and module hierarchy could have been deduced from the directory and file hierarchy, as it is the case in Python, IIRC. The search rules just have to be clear. I know this has the side effect that module names can't be keywords or non-identifiers, but who would use such module names? You can omit module declarations and those will be deduced indeed. However that will make package path dependent on compiler currend directory and this is why specifying qualified path explicitly is helpful. Compiling is already dependent on the current directory. And qualified path are not just helpful, they're required for packages, or did I miss something? Ah yes, damnation, I keep forgetting about this one. In my opinion it is a bug and it should indeed use reative folder path as package name. However fixing it can be hard because of possible build system breakage and stuff. Would be interesting to check that with dub Co. Actually, I don't think it's a bug. The current model is coherent: a package must be bound to a top-level directory. So the modules in the package must specify what this top-level directory is. What I meant is that I don't know what would be wrong in being able to do dmd -I/path/to/phobos/std and import stdio;, that is if relative folder paths were used. The module statement wouldn't be necessary (apart for files like foo-bar.d). I should've asked in d.learn :)
Re: struct and default constructor
On Friday, 10 October 2014 at 22:34:45 UTC, ketmar via Digitalmars-d wrote: I think I like the idea of the factory method now though, as I've learned you can hide a struct inside a function, and then call the function to set the struct up properly and return it. At least, I'm sure I've seen code that does that.. ah, yes, it's Voldemort type. ;-) auto thatWhoCantBeNamed () { static struct A { ... } return A(); } voila. you have type that you can use but cannot create without factory. but you need to have postblit enabled with this. It's not a Voldemort type if the struct A is static, is it? You can just alias A = typeof(thatWhoCantBeNamed()); and then create a new object of the same type. -- Nicolas
Re: Trouble with std.Variant
On Thursday, 18 September 2014 at 21:14:55 UTC, Ali Çehreli wrote: On 09/18/2014 02:06 PM, ddos wrote: The following code fails because Vec2.length() does not return int ... so Variant is only usable with types that do not have a method with name length() ?? i'm confused On Thursday, 18 September 2014 at 21:03:47 UTC, ddos wrote: struct Vec2 { float[2] vec; public float length() { return sqrt(vec[0]*vec[0]+vec[1]*vec[1]); } } int main(string[] argv) { Vec2 test; Variant v = test; return 0; } Compiles and runs without error with dmd git head, after adding the following two lines: ;) import std.math; import std.variant; Ali It shouldn't work in dmd git head. See Andrei's answer in https://issues.dlang.org/show_bug.cgi?id=5501
Re: long double in C APIs
On Monday, 15 September 2014 at 23:20:45 UTC, Walter Bright wrote: On 9/15/2014 3:24 PM, David Nadlinger wrote: 2. It effectively forces everybody to make all conversions to long double explicit in their code, This is due to D currently not allowing implicit conversion to a struct. It's a general issue, and should be dealt with as a general issue, as it comes up whenever a wrapped type is used. You say 'currently'. Is there a plan to allow this, if there's no ambiguity and if the wrapping struct defines some kind of opImplicitCast?
Re: Integral literals with Exp?
On Monday, 15 September 2014 at 09:19:12 UTC, eles wrote: On Monday, 15 September 2014 at 09:13:52 UTC, Walter Bright wrote: On 9/15/2014 1:54 AM, John Colvin wrote: On Monday, 15 September 2014 at 00:54:40 UTC, Walter Bright wrote: On 9/13/2014 12:23 AM, bearophile wrote: Readability is the goal, not minimizing the number of characters. Exactly: 6.02214129×10^23 http://en.wikipedia.org/wiki/Avogadro_constant Some constants are widely known in the eXX form. What integral type would hold that value?
Re: Convert hexadecimal to decimal
On Monday, 25 August 2014 at 06:57:48 UTC, confused wrote: hi team! I'm using this swift piece of code to seek out the Option 26 DHCP is deploying and output to the screen: https://github.com/CyberShadow/dhcptest/blob/master/dhcptest.d (props for code CyberShadow). When I get the value it says 0578. I've used an online converter to establish this is 1400 (which is what MTU value my dhcp server issues). ideally what I want to do is have that converted from hexadecimal to decimal in the code, but as quite the noob, I cant figure it out. any tips? You can use std.format: import std.format; auto data = 0578; auto spec = singleSpec(%X); assert(data.unformatValue!uint(spec) == 1400); (you should probably use the D.learn forum for this kind of question)
Re: Convert hexadecimal to decimal
On Monday, 25 August 2014 at 07:37:59 UTC, hane wrote: On Monday, 25 August 2014 at 06:57:48 UTC, confused wrote: hi team! I'm using this swift piece of code to seek out the Option 26 DHCP is deploying and output to the screen: https://github.com/CyberShadow/dhcptest/blob/master/dhcptest.d (props for code CyberShadow). When I get the value it says 0578. I've used an online converter to establish this is 1400 (which is what MTU value my dhcp server issues). ideally what I want to do is have that converted from hexadecimal to decimal in the code, but as quite the noob, I cant figure it out. any tips? Try std.conv.to. to!int(0578, 16) == 1400 Yes, that's a bit simpler than my solution :-P
Re: mixin assembler does not work?
On Sunday, 20 July 2014 at 15:02:58 UTC, Foo wrote: On Sunday, 20 July 2014 at 14:55:00 UTC, Foo wrote: For clarification: how would that work without mixin + string? I tried this: mixin template Vala2(uint count, alias arr) { asm { sub ESP, count; mov arr, count; mov arr + 4, ESP; } } but I get several errors. Unfortunately it seems that asm cannot be used in mixin templates?! The reason may be that mixin templates are just for inserting declarations, which asm blocks aren't. This limitation isn't specific to asm.
Re: ddox-generated Phobos documentation is available for review
On Monday, 10 March 2014 at 03:44:54 UTC, Andrei Alexandrescu wrote: Consider it alpha quality. Please don't announce yet before we put it in good shape. https://github.com/D-Programming-Language/dlang.org/pull/516 http://dlang.org/library http://dlang.org/library-prerelease I needed to change quite a bit about the makefile. It was building everything over and over again, and it's _slow_. Some functions are not ready, compare e.g. http://dlang.org/library/std/algorithm/balancedParens.html with http://dlang.org/library/std/algorithm/any.html Andrei For me it's a real improvement! One thing: symbol names (modules, functions, etc.) shouldn't be hyphenated, specially in tables. Nicolas
Re: xvalue and std::move in D
On Thursday, 6 March 2014 at 11:49:51 UTC, Edwin van Leeuwen wrote: On Thursday, 6 March 2014 at 11:28:21 UTC, Mike Parker wrote: See std.algorithm.move Thank you, can't believe I missed that. How do I specify that the function expects a temporary/xvalue () parameter though? What are you trying to do? D is not C++11. Pure functional programming in D follows a different path.
Re: RFC: Units of measurement for D (Phobos?)
On Wednesday, 26 February 2014 at 22:49:57 UTC, Nordlöw wrote: On Wednesday, 26 February 2014 at 21:41:57 UTC, Kelet wrote: Tangentially related: https://github.com/biozic/quantities Impressive! This seems similar to David Nadlingers std.units and std.si. When will all these efforts on implementing Units/SI be synchronized and reviewed? One question: I know what angles are but I have never seen them defined like this before! enum radian = meter / meter; // ditto enum steradian = square(meter) / square(meter); /// ditto What on earth does this mean? /Per Thanks! I think David Nadlingers' is more elaborate (scaled and affine units) and less prone to rounding errors. I haven't used it yet. Mine is more basic but has a parsing system that I use to define units quickly at compile-time and parse data files at runtime. -- Nicolas
Re: RFC: Units of measurement for D (Phobos?)
On Tuesday, 4 March 2014 at 13:20:02 UTC, Nordlöw wrote: Thanks! I think David Nadlingers' is more elaborate (scaled and affine units) and less prone to rounding errors. I haven't used it yet. Mine is more basic but has a parsing system that I use to So you cannot defined things lika kPa from Pa in compile-time? enum kPa = kilo(pascal); which is equivalent to enum kPa = 1000 * pascal; Note that my module defines no real unit type, just quantities: a unit is only a special quantity with a value of 1 and a set of dimensions (a base unit in the sense of the SI). I think it better fits what physical units really are. kPa would then be a quantity that stores 1000 and a set of dimensions corresponding to a pressure. If you declare: auto p = 101.3 * kPa; p stores a value that is 101.3 * 1000 internally, not 101.3. With David's library, I think you can declare kilopascal as a scaled unit derived from pascal, and then a quantity in kilopascal would actually store 101.3. The result is globally the same, but in fact the representations of the numeric values would be a bit different, and so would the rounding errors, when using floating point types. define units quickly at compile-time Can't David's package also quickly define in compile-time? I think it can. Have you thought about merging your effort vid Davids and propose it to Phobos? This issue has stale for quite some time know. I just think that David's package could have been proposed for Phobos a long time ago. I don't know what has stopped it then. I developed mine afterwards, not being aware of David's one. I would like to have support add support for geometric units like angles, coordinate systems, etc. Have you thought about integrating these with your module? My package is extendable. The SI module is just a predefined set of common quantities and prefixes. You can use your own. Some angle units are defined in quantites.si. I am not sure of what you call a coordinate systems in this respect. -- Nicolas
Re: adding static return?
On Monday, 3 March 2014 at 23:27:42 UTC, Xavier Bigand wrote: I thought it could be nice to have a static return. My Idea is to remove unnecessary bracket encapsulation made with some static if statements. It will works like this : module xxx.opengl; import buildSettings; // contains some global constants static if (renderMode == directX) return; ... So there will no more need to scope the module code and indent it. Is it a good idea? This is just to avoid brackets and the compulsion of indenting inside them, isn't it? ;-) Version blocks can be used with colons (see http://forum.dlang.org/thread/lep2p3$2765$1...@digitalmars.com for a caveat). May be this syntax could be extended to module-level static ifs. D would look more and more like Python...
Re: Top-3 for 2.066
On Tuesday, 25 February 2014 at 05:01:30 UTC, Manu wrote: In lieu of a clear roadmap, I'm just going to list the things actively holding me up on a daily basis. Others encouraged to add theirs, maybe we'll see patterns emerge. What are yours? Enhanced privacy: https://d.puremagic.com/issues/show_bug.cgi?id=1238 https://d.puremagic.com/issues/show_bug.cgi?id=5770 https://d.puremagic.com/issues/show_bug.cgi?id=11234 etc.
Re: How to resume iteration from previous point in associative array
On Wednesday, 19 February 2014 at 09:28:27 UTC, bearophile wrote: Tarman: We're doing some super computing big data style stuff with D. We have a system where we're comparing associative arrays with billions of entries. Built-in associative arrays were never tested with so many pairs, so perform exhaustive performance benchmarks first, and report in Bugzilla the performance and memory problems you hit. We've tried copying the keys into a non-associative array and sure this works, but it is far far far less optimal than an equivalent C++ solution we wrote where we use an std::unordered_set and can simply store the iterator. Have you tried the simplest thing, to let std.parallelism chunk a AA.byKey.zip(AA.byValue) ? Bye, bearophile Are byKey and byValue guaranteed to iterate the associative array in the same order?
Re: Review Candidates awaited!
On Saturday, 1 February 2014 at 19:52:59 UTC, Dicebot wrote: Looking at http://wiki.dlang.org/Review_Queue there are 4 proposals that are marked as Ready for review or Ready for comments. I can proceed with any of those any time proposal author sends me an e-mail acknowledging his attention. Walter Bright, Idan Arye, Paul D. Anderson, Michael Rynn - I am speaking about you ;) Also if there is something ready but not in queue - don't hesitate about it. Paul Andersons's decimal library looks very promising, but isn't usable in its current github version. I think it's more of a 'work in progress' and I hope that its development will be resumed.
Re: D as A Better C?
On Tuesday, 11 February 2014 at 21:19:36 UTC, Walter Bright wrote: On 2/11/2014 1:00 PM, Brian Rogoff wrote: Which D metaprogramming (templates, mixins, ctfe, ..) features would be in this D subset? All of them. And would all of D features be available at compile time? CTFE/string mixins seem to be rather limited if features relying on the GC are excluded.
It works!
The URL http://dlang.org links to a page that just says It works! So laconic a statement for such a wonderful language! ;-) Nicolas
Re: It works!
On Monday, 27 January 2014 at 12:40:12 UTC, Sönke Ludwig wrote: Am 27.01.2014 13:34, schrieb Nicolas Sicard: The URL http://dlang.org links to a page that just says It works! So laconic a statement for such a wonderful language! ;-) Nicolas Looks fine from here. Strange. I'll try again later, maybe a cache problem.
Re: It works!
On Monday, 27 January 2014 at 17:55:35 UTC, Brad Roberts wrote: On 1/27/14 9:43 AM, Stanislav Blinov wrote: On Monday, 27 January 2014 at 16:11:56 UTC, Andrei Alexandrescu wrote: Sure you meant http://issues.dlang.org/ That one is even more desriptive :) Issues.dlang.org isn't expected to work yet. I haven't done the work to move d.puremagic.com/issues over to it yet (need to work out some details first, probably be a few more weeks). dlang.org, on the other hand, is expected to work and didn't for a while. But not sure why since it isn't one of the sites I host and it's working now. I can confirm dlang.org is working well. An old version must have been in a cache until now.
Re: Using a delegate stored as a member of a destroyed struct?
On Monday, 27 January 2014 at 02:27:08 UTC, Steven Schveighoffer wrote: On Sun, 26 Jan 2014 18:41:00 -0500, Nicolas Sicard dran...@gmail.com wrote: Running a piece of code that can be reduced to: --- import std.stdio; void main() { import std.range; foreach(item; iota(0, 10).transform(2)) writeln(item); } auto transform(T)(T list, real x) { auto t = /* new */ Transformer(x); // line 12 return t.applyTo(list); } struct Transformer { real delegate(real) fun; this(real x) { fun = (real r) = r * x; } auto applyTo(T)(T list) { import std.algorithm; return list.map!(x = fun(x)); } } --- the program segfaults. I guess it's because fun is destroyed when 't' goes out of scope in 'transform'. I would have thought that the MapResult struct returned by 'applyTo' still holds a valid copy of fun, but I'm wrong... Is there a way to do it? No. Just don't do that. The runtime is permitted to move structs bit-for-bit, so you are not allowed to store a pointer that references 'this'. Unless you prevent copying via @disable this(this), your struct could be moved if someone, for instance, passed it as a parameter on the stack, or returned it. A delegate using 'this' as the context pointer is the same thing. The only way to solve this is to put the struct on the heap. But why even use a struct? You could just use a closure (which automatically goes on the heap if needed): auto Transformer(real x) { return (real r) = r * x; } auto applyTo(X, T)(X fun, T list) { import std.algorithm; return list.map!(x = fun(x)); } auto transform(T)(T list, real x) { auto t = Transformer(x); return t.applyTo(list); } -Steve Actually I used a struct because the code is more complex, and it builds an array of delegates, which are returned from global functions, like: --- struct Transformer { real delegate(real)[] funs; addFun(real x) { fun ~= makeFun(x); } // etc. } real delegate(real) makeFun(real x) { return (real r) = r * x; } --- This means my design was bad in the first place. Thanks for the explanation. Nicolas
Re: Using a delegate stored as a member of a destroyed struct?
On Monday, 27 January 2014 at 14:47:21 UTC, Steven Schveighoffer wrote: On Mon, 27 Jan 2014 03:17:51 -0500, Nicolas Sicard dran...@gmail.com wrote: Actually I used a struct because the code is more complex, and it builds an array of delegates, which are returned from global functions, like: --- struct Transformer { real delegate(real)[] funs; addFun(real x) { fun ~= makeFun(x); } // etc. } real delegate(real) makeFun(real x) { return (real r) = r * x; } --- This means my design was bad in the first place. Thanks for the explanation. Actually, the delegate there is fine! The makeFun function becomes a closure, and will be allocated on the heap. Where you are running into trouble is simply that the struct goes out of scope, and the array is therefore invalid. In fact, I think you were already doing that before (creating a closure). Here is a possible solution to your original example: auto applyTo(T)(T list) { import std.algorithm; auto funcopy = fun; return list.map!(x = funcopy(x)); } What's happening here is that funcopy is a stack local variable. However, since you're creating a delegate that uses local variables, the compiler creates a closure. In essence, it's like putting a new struct on the heap with the single member funcopy, and using that as the context pointer. Note that the original code also creates a closure, but 'fun' is a member of the hidden 'this' reference. Because the 'this' reference refers to destructed data, fun is garbage, hence the segfault. I actually was wrong about my original diagnosis. The delegate stored in your original code does NOT store a delegate with a context pointer that points to 'this', it's pointing to a closure. Because 'x' doesn't exist inside the struct, only inside the function. But my statements were still good advice, don't store pointers to yourself inside a struct :) -Steve This makes perfect sense. My real code works as expected now. Thanks for the clear explanation, and advice. Nicolas
Using a delegate stored as a member of a destroyed struct?
Running a piece of code that can be reduced to: --- import std.stdio; void main() { import std.range; foreach(item; iota(0, 10).transform(2)) writeln(item); } auto transform(T)(T list, real x) { auto t = /* new */ Transformer(x); // line 12 return t.applyTo(list); } struct Transformer { real delegate(real) fun; this(real x) { fun = (real r) = r * x; } auto applyTo(T)(T list) { import std.algorithm; return list.map!(x = fun(x)); } } --- the program segfaults. I guess it's because fun is destroyed when 't' goes out of scope in 'transform'. I would have thought that the MapResult struct returned by 'applyTo' still holds a valid copy of fun, but I'm wrong... Is there a way to do it? Of course, uncommenting 'new' on line 12 resolves the problem. Thanks, Nicolas
Conflict with private symbol from an imported module
Hi, I known this has been discussed before, and there still is an open issue in bugzilla (https://d.puremagic.com/issues/show_bug.cgi?id=1238). Is it considered a feature or a bug? Thanks
Re: Conflict with private symbol from an imported module
On Thursday, 23 January 2014 at 17:29:08 UTC, Gary Willoughby wrote: On Thursday, 23 January 2014 at 17:06:17 UTC, Nicolas Sicard wrote: Hi, I known this has been discussed before, and there still is an open issue in bugzilla (https://d.puremagic.com/issues/show_bug.cgi?id=1238). Is it considered a feature or a bug? Thanks Modules are broken in several ways: https://d.puremagic.com/issues/show_bug.cgi?id=314 It sure is broken. But I wondered if it would be let aside. I say this because I think I remember reading (from Walter?) that it would need a significant re-implementation to fix it.
Re: alias have new syntax?
On Saturday, 18 January 2014 at 23:00:11 UTC, bearophile wrote: cmplx: During the study D, I stumbled upon this design alias myInt = int; but the specification says nothing about such use alias. Is the syntax has been changed? Yes, it's a recent very small syntax improvement. Eventually I hope the older syntax will be deprecated. The old syntax is still used for the static this in structs. Bye, bearophile You meant alias this.
Re: Non-null objects, the Null Object pattern, and T.init
On Saturday, 18 January 2014 at 22:12:09 UTC, bearophile wrote: Walter Bright: I don't think a new syntax is required. We already have the template syntax: RangedInt!(0,10) should do it. Is this array literal accepted, and can D spot the out-of-range bug at compile time (Ada language allows both things)? RangedInt!(0, 10)[] arr = [1, 5, 12, 3, 2]; Even though the syntax would be less lean, D can already to this with templates and/or CTFE quite easily.
Re: Tyepof regex
On Monday, 13 January 2014 at 20:59:28 UTC, Brad Anderson wrote: There is also std.traits.ReturnType you can use for more complex types or voldemort types. Or: typeof(regex()) BTW, how does ReturnType handle overloads? -- Nicolas
Re: Temple: Compile time, embedded D templates
On Thursday, 2 January 2014 at 08:36:24 UTC, Dylan Knutson wrote: The reason for this is that std.variant.Variant isn't CTFEable, because it uses memcpy in opAssign. I'd consider that a Phobos bug; perhaps there is a way to make std.variant CTFE compatible? That'd allow for a much wider (and more useful) range of templates to be evaluated at compile time. I wish Variant worked at compile time myself. Did you file a bug/enhancement request? (I couldn't find one in bugzilla).
Re: static if - is the 'static' really needed?
On Friday, 13 December 2013 at 12:10:02 UTC, comco wrote: Imagine a world in which a simple 'if' has the semantics of a static if, if the condition is evaluable at CT. Is this a world you would rather live in? template Fac(int i) { if (i == 0) { // static if; doesn't introduce scope enum Fac = 1; } else { enum Fac = i * Fac!(i-1); } } // If the condition is not evaluable at CT, the ordinary runtime if semantics (introducing scope) are used. Me: pros: simpler syntax cons: harder to reason about; I recall Andrei's talk about the static if proposal to C++: we don't need _static else_ -- why do we even need 'static' in 'static if' by this reasoning? What would happen when the condition is sometimes evaluable at compile time and sometimes not? void foo(alias a)() { /* static */ if (a) int x = 1; else int x = 42; doSomethingWith(x); }
Re: is there anything like a DUB manual?
On Saturday, 7 December 2013 at 19:59:50 UTC, Fra wrote: I finally decided to try out DUB. The simple examples work great, but I could not find any user guide/list of possible options to be put in the package.json file. Just as an example, how do you pass specific compiler flags like '-J'? Did you have a look at http://code.dlang.org/package-format ?
Re: Shall I use std.json at my own risks ?
On Wednesday, 13 November 2013 at 06:30:21 UTC, Jonathan M Davis wrote: On Tuesday, November 12, 2013 22:11:45 H. S. Teoh wrote: What's the reason vibe.d's json tools aren't backported to Phobos? Probably because no one has ever bothered to try and get them ready to be reviewed for inclusion in Phobos. Also, vibe.d seems to have a lot of interdependencies with itself, making it so that some parts of it couldn't be put into Phobos very easily. I don't know how much of that affects their json module though, since I would have thought that that would be the sort of thing which would be fairly standalone. - Jonathan M Davis Actually, vibe.d's Json module was nearly independent from the rest of the framework, I mean until recently (I don't know if it is any more). It could be extracted in no time. But it seems that the main reason for not backporting it to Phobos was the need to wait for std.serialization.
__gshared immutable array of immutable elements
In this declaration (tango.io.Console.d from Tango2): __gshared immutable immutable(char)[] Eol = \r\n; Aren't the two `immutable` keywords redundant? Why would `__gshared` be necessary for such an immutable type? Thanks
Re: __gshared immutable array of immutable elements
On Tuesday, 12 November 2013 at 20:16:31 UTC, Dicebot wrote: On Tuesday, 12 November 2013 at 20:09:57 UTC, Martin Drašar wrote: Those two immutables are not redundant, because it is an array of immutable chars (string), that is itself immutable. It is redundant because immutable is transitive. immutable char[] is equivalent. But Tango has lot of meaningless and redundant attributes ( final private ;) ) That´s what I thought. So no hidden subtlety here, just hyperprotection :) Thanks
Re: How to iterate using foreach on a class?
On Friday, 1 November 2013 at 12:37:20 UTC, simendsjo wrote: On Friday, 1 November 2013 at 11:41:52 UTC, Jonathan M Davis wrote: On Friday, November 01, 2013 12:30:10 Gary Willoughby wrote: I have a class which contains an array as a core collection of data. I want to pass an instance of this class to a foreach loop and iterate through the enclosed array. How do i do this? I've asked this before and got an answer but i can't find anything now. In general, if you want to make something work with foreach, you either make it a range, or you give it an opSlice which returns a range (another alternative would be define opApply, but in general, code should be using the range primitives rather than opApply). Given that you're looking to iterate an array, and you presumably don't want the array to be consumed when iterating, the simplest would be to simply declare an opSlice on the class returns the array. e.g. class C { int[] foo; auto opSlice() { return foo; } } Then when you use the class in a foreach loop, it'll be sliced, and the return value of opSlice (the array in this case) will then be iterated over. - Jonathan M Davis So we basically have 4 ways..? 1) popFront + front 2) opSlice 3) alias this 4) opApply How about having a nested struct implementing a range interface + a method (@property) returning it + alias this on the property? http://dpaste.dzfl.pl/230061d2
Re: DMD 2.064 changelog typo?
On Tuesday, 29 October 2013 at 20:56:02 UTC, monarch_dodra wrote: On Tuesday, 29 October 2013 at 10:08:00 UTC, Sergei Nosov wrote: I guess it's a good thing, it's available online. While looking through it, I also noticed that there are new functions 'stripLeft/stripRight'. I believe it would be more consistent to call those stripFront/stripBack. Yes, it would be, but they are also a generalization of the eponymous string functions. Naming the new functions stripFront/stripBack instead of stripLeft/stripRight would itself be the more inconsistent. For example: //std.string.stripLeft assert(stripLeft( \tHello) == Hello); //std.algorithm.stripLeft(R, E)(R r, E e); assert(stripLeft( \tHello, ' ') == \tHello); //std.algorithm.stripLeft(alias pred, R)(R r); assert(stripLeft!(Not!isLower)( \tHello, ' ') == ello); But you make a valid point. How do these string functions handle RTL languages? Even for strings, 'front' and 'back' might be more appropriate than 'left' and 'right'.
Re: How to get a substring?
On Sunday, 27 October 2013 at 03:45:50 UTC, Timothee Cour wrote: On Sat, Oct 26, 2013 at 6:24 PM, Nicolas Sicard dran...@gmail.com wrote: On Sunday, 27 October 2013 at 00:18:41 UTC, Timothee Cour wrote: I've posted a while back a string=string substring function that doesn't allocating: google nonallocating unicode string manipulations code: auto slice(T)(T a,size_t u, size_t v)if(is(T==string)){//TODO:**generalize to isSomeString import std.exception; auto m=a.length; size_t i; enforce(u=v); import std.utf; while(u-- im){ auto si=stride(a,i); i+=si; v--; } // assert(u==-1); // enforce(u==-1); size_t i2=i; while(v-- i2m){ auto si=stride(a,i2); i2+=si; } // assert(v==-1); enforce(v==-1); return a[i..i2]; } unittest{ import std.range; auto a=≈açç√ef; auto b=a.slice(2,6); assert(a.slice(2,6)==çç√e); assert(a.slice(2,6).ptr==a.**slice(2,3).ptr); assert(a.slice(0,a.walkLength) is a); import std.exception; assertThrown(a.slice(2,8)); assertThrown(a.slice(2,1)); } Another one, with negative index like Javascript's String.slice(): http://dpaste.dzfl.pl/608435c5 not as efficient as what I proposed since it's iterating over the string twice (the 2nd index redoes the work done by 1st index). Could be adapted though. Yes. slice was a quick addition to before/after. I also wonder if std.uni.graphemeStride would be more appropriate.
Re: How to get a substring?
On Sunday, 27 October 2013 at 07:44:06 UTC, Jakob Ovrum wrote: On Saturday, 26 October 2013 at 21:23:13 UTC, Gautam Goel wrote: Dumb Newbie Question: I've searched through the library reference, but I haven't figured out how to extract a substring from a string. I'd like something like string.substring(Hello, 0, 2) to return Hel, for example. What method am I looking for? Thanks! There are a lot of good answers in this thread but I also think they miss the real issue here. I don't think so. It's indeed worth noticing that Phobos' algorithms work with Unicode nicely, but: a) working on indices is sometimes the actual functionality you need b) you need to allocate a new string from the range they return (the slice functions in this thread don't) c) do they really handle grapheme clusters? (I don't know)
Re: wrap/unwrap vs Go-style duck typing
On Saturday, 26 October 2013 at 14:39:31 UTC, Martin Nowak wrote: On 10/25/2013 07:46 AM, Andrei Alexandrescu wrote: Hello, I was curious how our fledgling wrap and unwrap routines compare with Go's duck typing - similarities, distinctions, performance. Please share any thoughts, thanks! Andrei What are you referring to by wrap/unwrap, functions like inputRangeObject? Martin http://dlang.org/phobos-prerelease/std_typecons.html#.wrap http://dlang.org/phobos-prerelease/std_typecons.html#.unwrap
Re: wrap/unwrap vs Go-style duck typing
On Saturday, 26 October 2013 at 15:08:23 UTC, Andrei Alexandrescu wrote: On 10/26/13 7:55 AM, Nicolas Sicard wrote: On Saturday, 26 October 2013 at 14:39:31 UTC, Martin Nowak wrote: On 10/25/2013 07:46 AM, Andrei Alexandrescu wrote: Hello, I was curious how our fledgling wrap and unwrap routines compare with Go's duck typing - similarities, distinctions, performance. Please share any thoughts, thanks! I wonder whether specifying Go-style wrap/unwrap would be a fair characterization when announcing 2.064. Since Go's duck typing is implicit and automatic, and highlighted as such, Go-style wrap/unwrap sounds a bit paradoxical... What about wrap/unwrap for Go-style structural typing? Nicolas
Re: How to get a substring?
On Sunday, 27 October 2013 at 00:18:41 UTC, Timothee Cour wrote: I've posted a while back a string=string substring function that doesn't allocating: google nonallocating unicode string manipulations code: auto slice(T)(T a,size_t u, size_t v)if(is(T==string)){//TODO:generalize to isSomeString import std.exception; auto m=a.length; size_t i; enforce(u=v); import std.utf; while(u-- im){ auto si=stride(a,i); i+=si; v--; } // assert(u==-1); // enforce(u==-1); size_t i2=i; while(v-- i2m){ auto si=stride(a,i2); i2+=si; } // assert(v==-1); enforce(v==-1); return a[i..i2]; } unittest{ import std.range; auto a=≈açç√ef; auto b=a.slice(2,6); assert(a.slice(2,6)==çç√e); assert(a.slice(2,6).ptr==a.slice(2,3).ptr); assert(a.slice(0,a.walkLength) is a); import std.exception; assertThrown(a.slice(2,8)); assertThrown(a.slice(2,1)); } Another one, with negative index like Javascript's String.slice(): http://dpaste.dzfl.pl/608435c5
Re: template definitions spanning modules.
On Monday, 26 August 2013 at 00:46:50 UTC, Jason den Dulk wrote: Hi Consider the following code module A; void xx(T:int)(T t) { .. } void xx(T:float)(T t) { .. } module B; import A; void xx(T:string)(T t) { .. } void main() { xx!(int)(4); xx(4.5); xx(abc); } The compiler won't let me do this. It will complain that xx!(int)(4) cannot be instantiated with xx(T:string). If I move xx(T:string) into its own module, the compiler complains about ambiguity. If I put them all in the same module, it works fine. I read about overload sets in the docs and tried the alias A.xx xx suggestion, but the compiler didn't like that either. Is there any way I can make this work without having to put them all in the same module? Thanks in advance. Jason. It's a known bug: http://d.puremagic.com/issues/show_bug.cgi?id=10658
Re: how to get enclosing function as symbol ? (eg: __function__.stringof ==__FUNCTION__)
On Sunday, 18 August 2013 at 02:50:32 UTC, JS wrote: On Sunday, 18 August 2013 at 01:52:50 UTC, Timothee Cour wrote: Is there any way to get the enclosing function as symbol ? I'd like something like that: alternative names would be: __function__ __context__ auto fun(alias caller=__function__)(){ //caller represents fun1!double return ReturnType!caller.init; } T fun1(T)(T x){ assert(__function__.stringof==__FUNCTION__); alias fun=__function__; assert( is(ReturnType! __function__) == T); return fun(); } void main(){fun1!double();} use a string mixin? I thought this would work but it doesn't: --- void foo(T)() { bar!__FUNCTION__(); } void bar(string Caller)() { mixin(alias caller = ~ Caller ~ ;); } void main() { foo!double(); } --- It works if foo isn't a template, though. The problem when foo is a template is that foo!double.foo seems to be an illegal construct for the compiler...
Re: Virtual templates members
On Thursday, 8 August 2013 at 01:48:49 UTC, JS wrote: The following code is used to reduce dependence on new and the GC. iNew is used as the replacement. The problem is, where ever New is used, it requires typing the type twice. e.g., A.New!A(...) instead of A.New(...) Is there any way to solve this issue? (iNew is suppose to provide the contract to implement a new like method that will allocate the class. Note there is no virtual function so no overhead) import std.stdio, std.conv; enum eNew { Default = 0, } interface iNew { final static T New(T, A...)(A args) { eNew type = eNew.Default; static if (A.length == 0 || !is(typeof(args[0]) == eNew)) alias nargs = args; else { type = cast(eNew)args[0]; alias nargs = args[1..$]; } writeln( , __traits(classInstanceSize, T)); switch (type) { default: return new T(nargs); } return new T(nargs); } } class A : iNew { int t; } class B : A { int q; double d; } void main() { A a = A.New!A(); B b = B.New!B(); readln(); } Why not make it a mixin template? --- import std.stdio, std.conv; enum eNew { Default = 0, } mixin template iNew(T) { final static T New(A...)(A args) { eNew type = eNew.Default; static if (A.length == 0 || !is(typeof(args[0]) == eNew)) alias nargs = args; else { type = cast(eNew)args[0]; alias nargs = args[1..$]; } writeln( , __traits(classInstanceSize, T)); switch (type) { default: return new T(nargs); } //return new T(nargs); } } class A { mixin iNew!A; int t; } class B : A { mixin iNew!B; int q; double d; } void main() { A a = A.New(); B b = B.New(); readln(); } ---
Re: Virtual templates members
On Thursday, 8 August 2013 at 16:58:37 UTC, JS wrote: On Thursday, 8 August 2013 at 07:21:19 UTC, Nicolas Sicard wrote: On Thursday, 8 August 2013 at 01:48:49 UTC, JS wrote: The following code is used to reduce dependence on new and the GC. iNew is used as the replacement. The problem is, where ever New is used, it requires typing the type twice. e.g., A.New!A(...) instead of A.New(...) Is there any way to solve this issue? (iNew is suppose to provide the contract to implement a new like method that will allocate the class. Note there is no virtual function so no overhead) import std.stdio, std.conv; enum eNew { Default = 0, } interface iNew { final static T New(T, A...)(A args) { eNew type = eNew.Default; static if (A.length == 0 || !is(typeof(args[0]) == eNew)) alias nargs = args; else { type = cast(eNew)args[0]; alias nargs = args[1..$]; } writeln( , __traits(classInstanceSize, T)); switch (type) { default: return new T(nargs); } return new T(nargs); } } class A : iNew { int t; } class B : A { int q; double d; } void main() { A a = A.New!A(); B b = B.New!B(); readln(); } Why not make it a mixin template? --- import std.stdio, std.conv; enum eNew { Default = 0, } mixin template iNew(T) { final static T New(A...)(A args) { eNew type = eNew.Default; static if (A.length == 0 || !is(typeof(args[0]) == eNew)) alias nargs = args; else { type = cast(eNew)args[0]; alias nargs = args[1..$]; } writeln( , __traits(classInstanceSize, T)); switch (type) { default: return new T(nargs); } //return new T(nargs); } } class A { mixin iNew!A; int t; } class B : A { mixin iNew!B; int q; double d; } void main() { A a = A.New(); B b = B.New(); readln(); } --- Because I don't want to have to specify this in each class. iNew is suppose to be a contract. What happens if someone writes a class and forgets to add the mixin then distributes the class in a library? There's no issue with that using an interface because it results in an error. I understand the goal. But if someone forgets to add the mixin, A.New() would not compile. And the probability of mistakenly calling 'new A' might even be as high as the probability of forgetting the mixin.
Re: [:] as empty associative array literal, plus warning for null
On Thursday, 4 July 2013 at 23:52:35 UTC, bearophile wrote: Andrei Alexandrescu: Where does the whole stronger typing comes in? This is poppycock. We need real arguments here. Maybe it's a matter of definitions, for me having null as literal for empty array, null pointer, empty associative array, and more is more weakly typed compared to having a literal like [] usable only for empty dynamic arrays (and strings), a literal as [:] usable only for empty associative arrays, and null for pointers, class references (and little else like a Nullable). Bye, bearophile While I agree with the need to have a literal for non-initialized arrays and another one for initialized but empty arrays, that is null and [] respectively, I can't see the necessity for [:]. The literal should be used to mark the difference between null and empty, not the difference between plain or associative, shouldn't it? For me, having to type int[string] foo = [:]; instead of int[string] foo = []; // same semantic would just be a source of confusion.
Re: Notes from C++ static analysis
On Wednesday, 26 June 2013 at 20:50:03 UTC, bearophile wrote: If you want a special behavour you should use a special function as partialWritefln that ignores arguments not present in the format string. Or maybe just define a new format specifier (%z, for 'zap'?) to ignore one or more arguments?
Re: @property - take it behind the woodshed and shoot it?
On Saturday, 26 January 2013 at 13:21:37 UTC, Jacob Carlborg wrote: It's always possible to avoid keywords in favor of syntax. Example: Declaring a getter: int foo {} Just as a regular function declaration but without the parentheses. Declaring a setter: void foo= (int value) {} Append an equal sign to the function name. How would you declare a template property? The getter would be ambiguous with a regular function declaration, wouldn't it?
Re: PDF spec
On Thursday, 24 January 2013 at 06:26:13 UTC, Andrei Alexandrescu wrote: There's quite a bit of work left to do, but the PDF spec already has 386 pages of goodness and starts to look seriously cool. Take a peek! http://dlang.org/dlangspec.pdf (still subject to http://d.puremagic.com/issues/show_bug.cgi?id=9369, so don't mind the absent underscores here and there) Andrei Great. This is just a cosmetic idea, but you could make the spec look like TDPL a bit with: \usepackage[scaled]{beramono} \usepackage{fourier} (should be available on all main TeX distributions) Nicolas
Re: D for scientific computing
On Wednesday, 23 January 2013 at 22:39:04 UTC, Alan wrote: I saw an old thread from 2004 while doing a google search that discussed D and scientific computing and was looking for some more recent information or opinions from people who have used it for such purposes. I am a graduate student and my thesis work is in numerical modeling. While I have some experience using Fortran and C, I am not obligated to use any particular language for my work. I like the design goals behind D and the syntax. I was would like to know if D can compete with C or Fortran for numerical work. Is anyone out there using D for heavy numeric work? The different D compilers available don't generate numeric code of the same quality, depending on the algorithms and data structures used. I have found in one of my projects that LDC produces code that is up to 5x or even 10x faster than DMD (though the average difference is less spectacular).
Re: D for scientific computing
On Thursday, 24 January 2013 at 10:42:10 UTC, Joseph Rushton Wakeling wrote: On 01/24/2013 11:16 AM, Walter Bright wrote: If you use the 64 bit model, dmd will use SIMD instructions for float and double, which are much faster. I generally find that dmd-compiled programs run at about half the speed of those built with gdc or ldc (the latter seem pretty much equivalent these days, some programs run faster compiled with one, some with the other). That's running off latest GitHub source for all compilers. That's been a fairly consistent speed difference for a long time. And yes, I'm using 64-bit. Same for me. The difference between ldc and dmd seems to be mainly due to optimizing and especially inlining (see http://d.puremagic.com/issues/show_bug.cgi?id=9320 for an example in that matter).
Re: Limited printing?
On Wednesday, 16 January 2013 at 11:16:41 UTC, bearophile wrote: In Mathematica and NumPy (and other systems used with REPL) if you print a very large array you receive a shortened output. In Mathematica: http://reference.wolfram.com/mathematica/tutorial/ShortAndShallowOutput.html Mathematica uses a representation like (but on default it shows more items. There is a way to print them all): Range[100] {0, 1, 2, 94, 97, 98, 99} While numpy visualization is a bit simpler: from numpy import array array([0] * 10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) array([0] * 1) array([0, 0, 0, ..., 0, 0, 0]) Currently In D this shows all the items: writeln(iota(10_000)); Do you desire some way to have a shortened printing if the generated text is going to be huge? Bye, bearophile writeln(iota(10_000).take(10)); ?
Re: Limited printing?
On Wednesday, 16 January 2013 at 11:46:10 UTC, bearophile wrote: Nicolas Sicard: writeln(iota(10_000).take(10)); ? You have missed the point. What if you have a [iota(10_000), iota(10_000)]? OK, but is there a simple and general way to tell how to skip elements for ranges other than sorted numeric ones?
Re: Limited printing?
On Wednesday, 16 January 2013 at 14:05:03 UTC, bearophile wrote: Mathematica and NumPy on default shorten the output if it's too much large, and show it all on request. What I forgot to say in my first post is that in D it's probably better to have those conditions swapped, this means printing all on default, and adding a way to produce a shorter output on request. A format specifier like this, then, adding width and/or precision to %(: writefln(%10.3(%s, %), iota(10_000)); // Prints: 0, 1, 2, ... 7, 8, 9. could be useful.
Re: Mixin Template: cannot mixin scope(exit)?
On Monday, 14 January 2013 at 06:26:33 UTC, 1100110 wrote: On 01/13/2013 11:35 PM, 1100110 wrote: Ok, I wish to create a standard timing system so that I can measure ~how long each function takes to execute. I wish to be able to place at the start of a function version(Time) mixin TimeExecution(funcName); mixin template TimeExecution(T) if(isSomeString!T) { import std.stdio, std.datetime, std.conv; auto sw = StopWatch(AutoStart.yes); // Error: Declaration expected, not '(' scope(exit) writeln(T, : , to!Duration(sw.peek)); } Why do I receive the Error when the scope statement is included? Is this an error, or what is the rationale behind the decision? Thank you. It appears that you cannot mixin *any* statement with scope([exit,success,etc]) in it. Mixin templates are supposed to introduce *declarations* not statements. Eg. even this shouldn't compile, should it? --- mixin template TimeExecution(T) if(isSomeString!T) { import std.stdio; writeln(T); // statement } ---
Re: Mixin Template: cannot mixin scope(exit)?
On Tuesday, 15 January 2013 at 11:19:50 UTC, mist wrote: I thought template itself should compile but its statement-like instantiation should not. The template shouldn't compile: the D grammar says that mixin templates inject declarations only. Hence the text of the error. By the way, if all you want is to split out some generic statement block without using dirty string mixins, template functions with alias parameters may do. I.e. http://dpaste.1azy.net/68ad8133 Yes, but only a string mixin can inject a scope statement.
Re: POD
On Saturday, 29 December 2012 at 01:53:15 UTC, David Nadlinger wrote: - There are also possible performance implications: Structs that just wrap a single field in order to enrich it with type information, such as Duration or a Quantity struct from a units of measurement library, will likely benefit from being passed in registers (if available), even if they will probably have constructors. In fact, having such one-field structs behave like a naked value might be vitally important to be able to decorate a C API with e.g. units information (even if such code would strictly speaking be architecture dependent). As far as I can see – and I'm merely guessing based on the isPOD comment here – the only reason for not just applying the C/C++ definition in the obvious way might be a quirk in the DMD backend implementation? I had started but never finished such a wrapping struct for units, and I gave it another try recently (https://github.com/biozic/siunits). Clearly, when using POD structs, the code of the function 'quality' in examples/rlc.d, executes way more rapidly (5x) than using non-POD structs. The only difference between POD and non-POD in my tests is the presence of non-default constructors, which is versioned out in the POD version. Code of the quality function with POD struct (compiled with -O -inline -release): --- pushRBP mov RBP,RSP fld tbyte ptr 020h[RBP] fld tbyte ptr 010h[RBP] fld tbyte ptr [0E77Ch][RIP] fmulp ST(1),ST fld tbyte ptr 030h[RBP] fmulp ST(1),ST fdivp ST(1),ST pop RBP ret --- Same code with the non POD version (same compiler flags): --- pushRBP mov RBP,RSP sub RSP,0B0h mov RSI,[00h][RIP] lea RDI,-040h[RBP] movsd movsd fld tbyte ptr [0E5C4h][RIP] fstptbyte ptr -040h[RBP] mov word ptr -036h[RBP],0 mov dword ptr -034h[RBP],0 lea RSI,-040h[RBP] lea RDI,-050h[RBP] movsd movsd lea RSI,-050h[RBP] lea RDI,-060h[RBP] movsd movsd mov RSI,[00h][RIP] lea RDI,-030h[RBP] movsd movsd fld tbyte ptr 010h[RBP] fld tbyte ptr -060h[RBP] fmulp ST(1),ST fstptbyte ptr -030h[RBP] mov word ptr -026h[RBP],0 mov dword ptr -024h[RBP],0 lea RSI,-030h[RBP] lea RDI,-070h[RBP] movsd movsd lea RSI,-070h[RBP] lea RDI,-080h[RBP] movsd movsd mov RSI,[00h][RIP] lea RDI,-020h[RBP] movsd movsd fld tbyte ptr 030h[RBP] fld tbyte ptr -080h[RBP] fmulp ST(1),ST fstptbyte ptr -020h[RBP] mov word ptr -016h[RBP],0 mov dword ptr -014h[RBP],0 lea RSI,-020h[RBP] lea RDI,-090h[RBP] movsd movsd lea RSI,-090h[RBP] lea RDI,-0A0h[RBP] movsd movsd mov RSI,[00h][RIP] lea RDI,-010h[RBP] movsd movsd fld tbyte ptr 020h[RBP] fld tbyte ptr -0A0h[RBP] fdivp ST(1),ST fstptbyte ptr -010h[RBP] mov word ptr -6[RBP],0 mov dword ptr -4[RBP],0 lea RSI,-010h[RBP] lea RDI,-0B0h[RBP] movsd movsd fld tbyte ptr -0B0h[RBP] mov RSP,RBP pop RBP ret --- I will use such a library in an environment that is not performance critical. But I hope that this will eventually be optimized. Thanks, Nicolas
Re: POD
On Monday, 14 January 2013 at 21:18:13 UTC, Walter Bright wrote: On 1/14/2013 11:24 AM, Nicolas Sicard wrote: I had started but never finished such a wrapping struct for units, and I gave it another try recently (https://github.com/biozic/siunits). Clearly, when using POD structs, the code of the function 'quality' in examples/rlc.d, executes way more rapidly (5x) than using non-POD structs. The only difference between POD and non-POD in my tests is the presence of non-default constructors, which is versioned out in the POD version. Code of the quality function with POD struct (compiled with -O -inline -release): Please make a bugzilla entry with this. Thanks! Done: http://d.puremagic.com/issues/show_bug.cgi?id=9320 English is not my mother language, so I hope the summary is OK.
Re: Official DMD compiler written in D
On Tuesday, 8 January 2013 at 21:57:17 UTC, H. S. Teoh wrote: On Tue, Jan 08, 2013 at 07:48:58PM +0100, Tim Krimm wrote: Now that D 2.0 is fairly stable, are there any plans of writing the official DMD compiler with the D 2.0 language vs the present language of C++? DMD 2.0 would have to be feature frozen and then DMD 3.0 could be written with the previous DMD 2.0 compiler. What are your thoughts? Philosophically, I like this idea. D should eat its own dogfood to prove its own worth. :) However, having the D compiler itself written in D, means we will have trouble bootstrapping it on new platforms. The advantage of having a C++ implementation is that C/C++ compilers are almost the first thing that gets implemented on a new platform, so you can almost always count on their existence. So you can just compile DMD and away you go. We *could* write a cross-compiler, of course, but it still requires that you first target the D compiler (written in D) to the new platform, and then cross-compile itself to that platform. Whereas with DMD, you just use the target platform's C++ compiler and you're up and running. T I think the OP implied that we could build DMD2 from its C++ source on any platform and then DMD3 from its D source with DMD2.
Re: dlangspec.pdf?
On Saturday, 5 January 2013 at 08:59:32 UTC, Philippe Sigaud wrote: From markdown, it can easily be translated into pdf, html, mobi or epub (heck, even docx) Philippe I was wondering: do you use Pandoc to do that (e.g. for your D-template tutorial)? Nicolas
Re: dlangspec.pdf?
On Saturday, 5 January 2013 at 14:10:38 UTC, Philippe Sigaud wrote: Don't tempt me. I'm playing with the idea of writing a Ddoc - Markdown converter. Something like Pandoc, but lighter. Couldn't a .ddoc file with redefined macros produce Markdown output?
Re: Parsing error
On Friday, 28 December 2012 at 08:46:22 UTC, Jonathan M Davis wrote: On Wednesday, December 26, 2012 14:08:37 Nicolas Sicard wrote: I'm not sure whether this has been reported: --- struct Foo { void bar(T)() {} void baz() {} } void main() { Foo foo; (foo).bar!int(); // Compiler parsing error ((foo)).bar!int(); // OK foo.bar!int(); // OK (foo).baz(); // OK } --- DMD 2.060 on OS X. Check in bugzilla. If you can't find it, then report it. http://d.puremagic.com/issues - Jonathan M Davis http://d.puremagic.com/issues/show_bug.cgi?id=9232
Re: DMD build
On Friday, 28 December 2012 at 15:29:58 UTC, Jacob Carlborg wrote: On 2012-12-28 16:18, Russel Winder wrote: Is there a reason for using g++ to compile and link the C code of DMD? As far as I know it doesn't work with Clang. Did you have any other compiler in mind? Actually it works with Clang (v4.5), albeit with many warnings. Just pass HOST_CC=clang++ to the makefile.
Parsing error
I'm not sure whether this has been reported: --- struct Foo { void bar(T)() {} void baz() {} } void main() { Foo foo; (foo).bar!int(); // Compiler parsing error ((foo)).bar!int(); // OK foo.bar!int(); // OK (foo).baz(); // OK } --- DMD 2.060 on OS X. Thanks, Nicolas
Re: Is there interest in a std.http?
On Tuesday, 20 November 2012 at 03:49:57 UTC, Tyler Jameson Little wrote: Would a minor refactor of vibe.d be acceptable? This is pretty much what I'm looking for: https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/http/common.d https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/http/server.d Except that I'd remove some parts of it, like JSON parsing. I think that vibe.d could benefit from moving some of the code there into Phobos. I guess it comes down to whether it makes sense to make a standard HTTP library. BTW, the actual JSON module in viba.data.json in richer in functionality and easier to use than the one in std.json. The module has virtually no dependency on other parts of vibe.d. I whish it was also moved to Phobos or at least inspired a refactoring of std.json. Nicolas
Array!bool and size_t
The implementation of std.container.Array!bool makes use of ulong instead of size_t as far as sizes and indices are concerned. This makes Array!bool inconsistent with other array-like types (including Array!T if !is(T==bool)) in 32-bit code. What would be the disadvantages of using size_t? Thanks, Nicolas
Re: Array!bool and size_t
On Tuesday, 15 May 2012 at 10:04:52 UTC, Dmitry Olshansky wrote: On 15.05.2012 13:44, Nicolas Sicard wrote: The implementation of std.container.Array!bool makes use of ulong instead of size_t as far as sizes and indices are concerned. This makes Array!bool inconsistent with other array-like types (including Array!T if !is(T==bool)) in 32-bit code. What would be the disadvantages of using size_t? Thanks, Nicolas theoretically you can pack 8*2^30+ bits in 1Gb+ of memory. While it's doubtful if you can always fetch such big piece of contiguous memory from OS it's still possible. And 32bit bit-indexes just fail to address it. Yes, I understand this limitation. But from another theoretical point of view, length not returning a size_t is odd for a container (std.bitmanip.BitArray.length did). But I am ok if it is more needful for an array of bool to be able to address the full memory... Thanks, Nicolas
Re: Voldemort Types in D
On Wednesday, 9 May 2012 at 14:30:33 UTC, Andrei Alexandrescu wrote: http://www.reddit.com/r/programming/comments/telhj/voldemort_types_in_d/ Andrei One drawback of Voldemort types, is that they are incompatible with the generation of .di files (option -H). See http://d.puremagic.com/issues/show_bug.cgi?id=5461. Nicolas
Re: [Issue 8063] Purity of assert's second parameter
--- Comment #1 from bearophile_h...@eml.cc 2012-05-08 04:12:12 PDT --- (In reply to comment #0) Calling impure functions in the second parameter of an assert statement within the body of a pure pure is an error, even in release mode. This is good. Since it is allowed to call impure functions in debug blocks inside pure functions, I thought it would be coherent that assert could do the same.
Re: D static lib called from C on Mac OS X
Bug report: http://d.puremagic.com/issues/show_bug.cgi?id=7995
Re: Power of D
On Thursday, 26 April 2012 at 10:50:49 UTC, David wrote: Am 26.04.2012 07:55, schrieb Era Scarecrow: Associative arrays? C++: #include map #include string mapstring, string m; Java: import java.util.*; MapString, String map = new HashMapString, String(); D: string[string] map (Don't know the other two... sorry) -- Python: map = dict() # or map = {} I think that many D powerful features are also easily done in Python or have easy to use equivalents, thanks to built-in dictionaries, list comprehensions, eval, etc. and so many available libraries. Albeit at the price of a slw execution comparing to D (unless you can utilize native extensions).
D static lib called from C on Mac OS X
Hi, I am trying to use a D static library from C on Mac OSX Lion, but it always fails. --- file mylib.d --- module mylib; import core.runtime; extern(C) { bool mylib_init() { return Runtime.initialize(); } bool mylib_free() { return Runtime.terminate(); } } --- --- file main.c --- extern void mylib_init(); extern void mylib_free(); int main() { mylib_init(); mylib_free(); return 0; } --- I am compiling using: $ dmd -c -lib mylib.d -oflibmylib.a $ gcc -o main main.c -L. -lmylib -lphobos2 When I run ./main, I get a EXC_BAD_ACCESS (SIGSEGV) that seems related to thread local storage during runtime initialization. Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 main 0x000103072dac __tls_get_addr + 196 1 main 0x000103071d80 thread_attachThis + 312 2 main 0x000103071c3c thread_init + 24 3 main0x000103073296 gc_init + 86 4 main0x000103079f79 rt_init + 29 5 main 0x0001030705bb D4core7runtime7Runtime10initializeFDFC6object9ThrowableZvZb + 15 6 main 0x000103069e5d mylib_init + 13 7 main0x000103069e2f main + 15 8 main0x000103069e14 start + 52 Am I doing something wrong or trying to do something currently unsupported? Thanks, Nicolas
Re: D static lib called from C on Mac OS X
s/void/int in main.c
Re: D static lib called from C on Mac OS X
More testing. This: --- file mylib.d module mylib; import core.runtime; import std.stdio; extern(C) { bool mylib_init() { return Runtime.initialize(); } bool mylib_free() { return Runtime.terminate(); } void mylib_hello() { writeln(Hello from mylib); } } void main() {} // Fake main --- --- file main.c --- extern int mylib_init(); extern int mylib_free(); extern void mylib_hello(); int main() { mylib_init(); mylib_hello(); mylib_free(); return 0; } --- $ dmd -c mylib.d $ gcc -o main main.c mylib.o -lphobos2 -lpthread -lrt $ ./main works on Linux (Unbuntu 11.10), but segfaults on OS X Lion.
Re: D static lib called from C on Mac OS X
On Wednesday, 25 April 2012 at 17:59:38 UTC, Andrej Mitrovic wrote: On 4/25/12, Nicolas Sicard dran...@gmail.com wrote: --- file main.c --- extern void mylib_init(); extern void mylib_free(); Try changing void to bool there. This was a typo in my first post. The problem is elsewhere. Thanks
Re: [Kinda OT] httpd permissions
On Wednesday, 25 April 2012 at 18:11:16 UTC, Nathan M. Swan wrote: 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 Have you checked that your web server has write access to /Users/nathanmswan/Sites/ ?
final forbidden with value template parameters?
Hi module main; class Foo(string s) {} final class Bar(string s) {} // Error The compiler says: variable main.s final cannot be applied to variable Why is this forbidden? Nicolas (DMD 2.022 - Linux)