Re: shouldn't this code at least trigger a warning?
On Wednesday, 29 April 2015 at 06:37:44 UTC, ketmar wrote: subj. the code: void main () { import std.stdio; char ch = '!'; switch (ch) { int n = 42; case '!': writeln(n, ": wow!"); break; default: } } i think that such abomination should: 1. be forbidden, or 2. trigger a warning, or 3. execute initializer anyway. currently the code is allowed, no warnings triggered, yet `n` is uninitialized. and having uninitialized variable without "=void" "should not be". Agreed, this should be an error. Variables declared in one case block aren't even visible in other case blocks, this was probably an oversight.
Re: shouldn't this code at least trigger a warning?
On Wednesday, 29 April 2015 at 06:37:44 UTC, ketmar wrote: subj. the code: void main () { import std.stdio; char ch = '!'; switch (ch) { int n = 42; case '!': writeln(n, ": wow!"); break; default: } } i think that such abomination should: 1. be forbidden, or 2. trigger a warning, or 3. execute initializer anyway. currently the code is allowed, no warnings triggered, yet `n` is uninitialized. and having uninitialized variable without "=void" "should not be". Please raise an issue in bugzilla. This is obviously an error.
Re: Runtime metaprogramming in D
On Wednesday, 29 April 2015 at 02:20:25 UTC, Vladimir Panteleev wrote: On Wednesday, 29 April 2015 at 01:38:17 UTC, Dennis Ritchie wrote: Hi, Is it possible to write self-modifying code in D, who will perform at runtime? Not easily. Just the obvious approach to invoke the compiler and run/load the created executable / shared library. Or is it a characteristic of languages that compile to bytecode? I would say that it is a characteristic of languages which provide a compiler-as-a-library. Thanks.
Re: Reducing source code: weak+alias values in array
On 04/27/15 19:49, Jens Bauer via Digitalmars-d-learn wrote: > I was wondering if there's a way to reduce my bulky startup files a bit. > > If using the GNU Assembler (GAS), then one can reduce the code using a macro > like this: > > > /* The EXC macro makes a weak+alias for the > * symbol 'value', then it stores the value in memory: */ > .macroEXCvalue,defaultValue > .ifnb\defaultValue > .weakref\value,\defaultValue > .else > .weakref\value,defaultExceptionVector > .endif > .4byte\value > .endm > > > /* The exception vector now looks quite simple: */ > isr_vector: > .4byte_stack > EXCReset_Handler,defaultResetHandler > EXCNMI_Handler > EXCHardFault_Handler > EXCMemManage_Handler > EXCBusFault_Handler > EXCUsageFault_Handler > .4byte0 > .4byte0 > .4byte0 > .4byte0 > EXCSVC_Handler > EXCDebugMon_Handler > .4byte0 > EXCPendSV_Handler > EXCSysTick_Handler > > An example on one of my bulky startup files: > https://github.com/jens-gpio/MCU/blob/master/startup/stm/stm32f439_startup.d Just create a helper module, which the startup files can all use to generate the data from a dsl. Eg import my.helper.mod; mixin(VectorFuncs!(q{ PTR stack = {`_stack`}; EXC Reset_Handler = {`defaultResetHandler`}; EXC NMI_Handler; EXC HardFault_Handler; PAD pad01; PAD pad02; //... })); // Then, in my.helper.mod: @property /*@section("discard.etc")*/ VectorFuncs(string dsl)() { static struct A { struct PTR { string n; @property s() {return `cast(VectorFunc)&`~n;} } struct PAD { string n; @property s() {return `cast(VectorFunc)null`;} } struct EXC { string n = `defaultExceptionHandler`; @property s() {return null;} } mixin(dsl); } string code; foreach (I, M; A.init.tupleof) static if (is(typeof(M)==A.EXC)) code ~= `@weakalias("`~M.n~`") extern (C) void ` ~ __traits(identifier, A.tupleof[I]) ~ "();\n"; code ~= "\n@isr_vector VectorFunc[] g_pfnVectors = [\n"; foreach (I, M; A.init.tupleof) code ~= " " ~ (M.s?M.s:"&"~__traits(identifier, A.tupleof[I])) ~ ",\n"; code ~= "];\n"; return code; } and what the compiler will see when building the startup modules will look like @weakalias("defaultResetHandler") extern (C) void Reset_Handler(); @weakalias("defaultExceptionHandler") extern (C) void NMI_Handler(); @weakalias("defaultExceptionHandler") extern (C) void HardFault_Handler(); @isr_vector VectorFunc[] g_pfnVectors = [ cast(VectorFunc)&_stack, &Reset_Handler, &NMI_Handler, &HardFault_Handler, cast(VectorFunc)null, cast(VectorFunc)null, ]; artur
Re: C++ interface problem
On Monday, 27 April 2015 at 21:19:02 UTC, extrawurst wrote: here is the shortened version of the returned class CSteamID: https://gist.github.com/Extrawurst/936f56ceaa87cf287257 this is the shortened interface (no destructors in the rest of the code either): https://gist.github.com/Extrawurst/b20dc5ab84132ecab30d the method `GetFriendByIndex` is the one crashing on win32. I assume that's because CSteamID is returned by value. Are you defining CSteamID in D as a struct? If not you have to because only structs can be returned by value. The next problem is that CSteamID is 64bits wide, this might be a problem as it can not be returned in a single register. You could try changeing the definition of GetFriendByIndex on the D side to ulong GetFriendByIndex(...) and reinterpret the ulong on the D side. If that does not work however you are most likely out of luck because the way your c++ library returns a value type > 32-bit is not compatible with what dmd expects. Do you have debug symbols for the third party c++ library? Can you step into the virtual function call to actually see if it ends up in the correct function on the c++ side? Kind Regards Benjamin Thaut
Re: Fuzzy Levenshtein variant of std.conv.to
On Tuesday, 28 April 2015 at 23:09:27 UTC, Per Nordlöw wrote: On Tuesday, 28 April 2015 at 16:20:24 UTC, Per Nordlöw wrote: I update my Github repo. I had forgotten to push my latest changes. I solved it.
Re: shouldn't this code at least trigger a warning?
On Wed, Apr 29, 2015 at 06:37:44AM +, ketmar via Digitalmars-d-learn wrote: > subj. the code: > > void main () { > import std.stdio; > char ch = '!'; > switch (ch) { > int n = 42; > case '!': writeln(n, ": wow!"); break; > default: > } > } > > > i think that such abomination should: > 1. be forbidden, or > 2. trigger a warning, or > 3. execute initializer anyway. > > currently the code is allowed, no warnings triggered, yet `n` is > uninitialized. and having uninitialized variable without "=void" > "should not be". Switch statements in D allow all sorts of abominations, if only you would try it. I think it was originally designed to support a particular loop idiom (sorry I forgot what it was called, and don't have time to look it up right now), but in the process this also opened the door to all sorts of nasty infelicities that probably breaks the type system, control flow, and many other things. Basically, the block inside a switch statement essentially amounts to free-for-all spaghetti code where you're free to jump around case labels willy-nilly, declare variables and jump over their initializations, break out of loops with goto case, or enter into the middle of a loop, and all sorts of other crazy things that, ostensibly, you shouldn't be able to do in a language like D. T -- Let's eat some disquits while we format the biskettes.
Re: Reducing source code: weak+alias values in array
On Wednesday, 29 April 2015 at 13:58:14 UTC, Artur Skawina wrote: On 04/27/15 19:49, Jens Bauer via Digitalmars-d-learn wrote: I was wondering if there's a way to reduce my bulky startup files a bit. If using the GNU Assembler (GAS), then one can reduce the code using a macro like this: {snip} An example on one of my bulky startup files: https://github.com/jens-gpio/MCU/blob/master/startup/stm/stm32f439_startup.d Just create a helper module, which the startup files can all use to generate the data from a dsl. Eg That is very cool and quite short. Thank you! I'll try it out ... I'm already starting to understand some of what's going on, but it'll probably be clearer when I've typed the code (I do not just do copy-and-paste, as I've found out that I learn better by forcing each letter through my brain).
Re: shouldn't this code at least trigger a warning?
On 04/29/2015 07:57 AM, H. S. Teoh via Digitalmars-d-learn wrote: Switch statements in D allow all sorts of abominations, if only you would try it. I think it was originally designed to support a particular loop idiom (sorry I forgot what it was called http://en.wikipedia.org/wiki/Duff%27s_device Ali
Create custom data types
Hi, Is it possible to create simple D user-defined data types without the use of classes and other OOP? For example, in Ada is done as follows: - type balance is new Integer range -32_000 .. 32_000;
Re: Runtime metaprogramming in D
On 04/28/2015 07:20 PM, Vladimir Panteleev wrote: On Wednesday, 29 April 2015 at 01:38:17 UTC, Dennis Ritchie wrote: Hi, Is it possible to write self-modifying code in D, who will perform at runtime? Not easily. Just the obvious approach to invoke the compiler and run/load the created executable / shared library. Or is it a characteristic of languages that compile to bytecode? I would say that it is a characteristic of languages which provide a compiler-as-a-library. SDC will make D such a language. :) Ali
Re: Runtime metaprogramming in D
On Wednesday, 29 April 2015 at 17:35:50 UTC, Ali Çehreli wrote: SDC will make D such a language. :) Ali It remains to build SDC in the standard library of the future DDMD :)
Re: Create custom data types
On Wednesday, 29 April 2015 at 17:17:07 UTC, Dennis Ritchie wrote: Hi, Is it possible to create simple D user-defined data types without the use of classes and other OOP? For example, in Ada is done as follows: - type balance is new Integer range -32_000 .. 32_000; I think you can use struct for this together with opAssign etc. functions in it. So, you can define a new variable that uses 3-bytes in memory example. But for 32_000, I think limitations are based on processor, and not the language.
Re: Create custom data types
On 04/29/2015 10:17 AM, Dennis Ritchie wrote: Hi, Is it possible to create simple D user-defined data types without the use of classes and other OOP? For example, in Ada is done as follows: - type balance is new Integer range -32_000 .. 32_000; Something similar to the following solution should be in Phobos: import std.exception; struct Balance { int value_; alias value this; @property int value() const { enforce((value_ >= -32_000) && (value_ <= 32_000)); return value_; } @property void value(int v) { value_ = v; } } unittest { auto b = Balance(42); assert(b == 42); b = 40_000; void foo(int) {} assertThrown(foo(b)); } void main() {} It should be easy to make a template of it. (I really think it should already be in Phobos. :) ) It can be different in several ways: If mutation is never allowed, then the range enforcement can be moved to its constructor. Otherwise, if mutation is allowed and used much less than access, then the enforcement can be moved to the setter. Ali
stdx.data.json
Hi. What's the best way to pass the contents of a file to the stream parser without reading the whole thing into memory first? I get an error if using byLine because the kind of range this function returns is not what the stream parser is expecting. There is an optional filename argument to parseJSONStream, but I am not sure what this is for, since it still requires the first argument for the input if the filename is passed. Thanks. Laeeth.
Re: C++ interface problem
On Wednesday, 29 April 2015 at 13:55:46 UTC, Benjamin Thaut wrote: On Monday, 27 April 2015 at 21:19:02 UTC, extrawurst wrote: here is the shortened version of the returned class CSteamID: https://gist.github.com/Extrawurst/936f56ceaa87cf287257 this is the shortened interface (no destructors in the rest of the code either): https://gist.github.com/Extrawurst/b20dc5ab84132ecab30d the method `GetFriendByIndex` is the one crashing on win32. I assume that's because CSteamID is returned by value. Are you defining CSteamID in D as a struct? If not you have to because only structs can be returned by value. The next problem is that CSteamID is 64bits wide, this might be a problem as it can not be returned in a single register. You could try changeing the definition of GetFriendByIndex on the D side to ulong GetFriendByIndex(...) and reinterpret the ulong on the D side. If that does not work however you are most likely out of luck because the way your c++ library returns a value type > 32-bit is not compatible with what dmd expects. Do you have debug symbols for the third party c++ library? Can you step into the virtual function call to actually see if it ends up in the correct function on the c++ side? Kind Regards Benjamin Thaut Seems i am out of luck. I tried all that. The Steamworks SDK is closed source without debugging symbols. so it wont work.. too bad, this library would have been a good example case of seamless c++-interfacing from D...
ldc std.getopt
When building the following (reduced by hand - I hope I didn't take out something useful when doing so): import std.stdio; import std.getopt; int main(string[] args) { string apiKey; string startCode; bool reverseOrder=false; bool noReverse=false; auto helpInformation = getopt( args, "apikey|k","specify API key directly",&apiKey, "startcode|c", "start begining from specified code",&startCode, "reverse|r","reverse sort order",&reverseOrder, "noreverse|n","don't reverse sort order",&noReverse ); if (helpInformation.helpWanted) { defaultGetoptPrinter( "downloader tool", helpInformation.options); return(1); } } I get the following errors under LDC (this is LDC beta, but same problem under master) although the code compiles fine under DMD. Am I doing something wrong? Laeeth. Building app ~master configuration "application", build type release. Running ldmd... /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(547): Deprecation: using * on an array is deprecated; use *(receiver).ptr instead /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(547): Error: cannot modify immutable expression *cast(immutable(char)*)receiver /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(548): Deprecation: using * on an array is deprecated; use *(receiver).ptr instead /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(548): Deprecation: using * on an array is deprecated; use *(receiver).ptr instead /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(548): Error: cannot modify immutable expression *cast(immutable(char)*)receiver /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(441): Error: template instance std.getopt.handleOption!string error instantiating /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(392): instantiated from here: getoptImpl!(string, string, bool*, string, string, string*, string, string, string*, string, string, bool*, string, string, bool*) source/quandljuice.d(74):instantiated from here: getopt!(string, string, bool*, string, string, string*, string, string, string*, string, string, bool*, string, string, bool*) /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(433): Error: array index [1] is outside array bounds [0 .. 1] /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: string slice [2 .. 1] is out of bounds /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: template instance std.getopt.getoptImpl!(bool*) error instantiating /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(392): 8 recursive instantiations from here: getoptImpl!(string, string, bool*, string, string, string*, string, string, string*, string, string, bool*, string, string, bool*) source/quandljuice.d(74):instantiated from here: getopt!(string, string, bool*, string, string, string*, string, string, string*, string, string, bool*, string, string, bool*) /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(442): Error: cannot return non-void from void function /opt/ldc2-0.15.2-beta1-linux-x86_64/bin/../import/std/getopt.d(392): Error: cannot return non-void from void function source/quandljuice.d(84): Error: undefined identifier defaultGetoptPrinter FAIL .dub/build/application-release-linux.posix-x86_64-ldc_2066-2DF1454C29130A0C55C59AAC96C6108A/ quandljuice executable
Re: Create custom data types
On Wednesday, 29 April 2015 at 17:52:27 UTC, Ali Çehreli wrote: On 04/29/2015 10:17 AM, Dennis Ritchie wrote: Hi, Is it possible to create simple D user-defined data types without the use of classes and other OOP? For example, in Ada is done as follows: - type balance is new Integer range -32_000 .. 32_000; Something similar to the following solution should be in Phobos: import std.exception; struct Balance { int value_; alias value this; @property int value() const { enforce((value_ >= -32_000) && (value_ <= 32_000)); return value_; } @property void value(int v) { value_ = v; } } unittest { auto b = Balance(42); assert(b == 42); b = 40_000; void foo(int) {} assertThrown(foo(b)); } void main() {} Thanks. On Wednesday, 29 April 2015 at 17:52:27 UTC, Ali Çehreli wrote: It should be easy to make a template of it. (I really think it should already be in Phobos. :) ) Where can I find documentation on this subject?
Re: Create a case-insensitive startsWith
On Tuesday, 28 April 2015 at 22:34:07 UTC, Justin Whear wrote: if (startsWith!"icmp(a, b) == 0"(input, "0x")) if (startsWith!"std.uni.icmp(a, b) == 0"(input, "0x")) if (startsWith!((a,b) => icmp(a,b) == 0)(input, "0x")) The issue is that those icmp functions take strings as arguments while startsWith expects the predicate to take individual characters. Thanks. That seems obvious now that you mention it but honestly I could not tell that from the documentation :-( I believe the best solution here is to use the lazy toLowerCase function in std.uni and the default predicate: if (startsWith(input.toLowerCase, "0x".toLowerCase)) I think I will have to make a "string idioms" wiki page...
Re: ldc std.getopt
On Wednesday, 29 April 2015 at 19:43:44 UTC, Laeeth Isharc wrote: I get the following errors under LDC (this is LDC beta, but same problem under master) although the code compiles fine under DMD. Am I doing something wrong? The help generating feature of std.getopt is new in 2.067. Use branch "merge-2.067" for that. Otherwise, don't use std.getopt's help generation just yet.
String from executeshell
I'm trying to run this command: wget -O - URL | gpg -d and get the result of the action, but I can't quite work out to do it. currently it looks like: executeShell(escapeShellCommand("wget", "-O", "-", url, "|", "gpg", "-D")); But I can't work out how to pull the string returned with this. Any help?
Re: [dvm] Can't install compilers on Mac
On Wednesday, 29 April 2015 at 06:41:30 UTC, Jacob Carlborg wrote: On 2015-04-28 19:46, Chris wrote: I keep getting this message. Why? Fetching: http://ftp.digitalmars.com/dmd.2.067.0.zip [>] 56256/54884 KB Installing: dmd-2.067.0 An unknown error occurred: tango.core.Exception.IOException@/Users/doob/development/d/tango/tango/core/Exception.d(59): /Users/name/.dvm/bin/dmd-2.067.0 :: No such file or directory OS X Version 0.4.3 Have you installed DVM itself, running "./dvm install dvm"? Can you please add the verbose flag, "-v", when installing a compiler and posting the output. Yes. Doesn't work. Maybe I should just download it and compile it myself?
Re: Possible to write a classic fizzbuzz example using a UFCS chain?
On Tuesday, 28 April 2015 at 10:46:54 UTC, Gary Willoughby wrote: After reading the following thread: http://forum.dlang.org/thread/nczgumcdfystcjqyb...@forum.dlang.org I wondered if it was possible to write a classic fizzbuzz[1] example using a UFCS chain? I've tried and failed. [1]: http://en.wikipedia.org/wiki/Fizz_buzz import std.stdio, std.algorithm, std.range, std.conv; void main() { immutable words = [3: "fizz", 5: "buzz"]; iota(1, 100). map!((int i) { immutable res = reduce!((a, b) => a ~ ((i % b == 0) ? words[b] : ""))("", words.keys); return res.empty ? i.to!string : res; }). writeln; } Atila
Re: Create custom data types
On 04/29/2015 12:53 PM, Dennis Ritchie wrote: On Wednesday, 29 April 2015 at 17:52:27 UTC, Ali Çehreli wrote: It should be easy to make a template of it. (I really think it should already be in Phobos. :) ) Where can I find documentation on this subject? Once a piece of code works for a particular type or value, it is easy to convert it to a template by moving the type and the value to the template parameter list and replace all occurrences of those with template parameters: - int -> T - -32_000 -> minValue - 32_000 -> maxValue Here it is: import std.exception; struct CustomInteger(T, T minValue, T maxValue) { T value_; alias value this; @property T value() const { enforce((value_ >= minValue) && (value_ <= maxValue)); return value_; } @property void value(T v) { value_ = v; } } unittest { alias Balance = CustomInteger!(int, -32_000, 32_000); auto b = Balance(42); assert(b == 42); b = 40_000; void foo(int) {} assertThrown(foo(b)); } void main() {} Ali
Re: String from executeshell
On 04/29/2015 02:05 PM, William Dunne wrote: I'm trying to run this command: wget -O - URL | gpg -d and get the result of the action, but I can't quite work out to do it. currently it looks like: executeShell(escapeShellCommand("wget", "-O", "-", url, "|", "gpg", "-D")); But I can't work out how to pull the string returned with this. Any help? executeShell returns the status and the output as a type (perhaps a tuple? :) ): http://dlang.org/phobos/std_process.html#.executeShell You use the return value for both the status and the output: auto wget = executeShell(escapeShellCommand(/* ... */)); if (wget.status == 0) { /* success */ writeln(wget.output);// <-- HERE } Ali
Re: String from executeshell
On 04/29/2015 02:54 PM, Ali Çehreli wrote: executeShell returns the status and the output as a type Certainly not. The output is an object of a special type, which the documentation refers to as 'auto'. Grrr... :) Ok, maybe it's a Voldemort type. Anyway... Ali
Re: String from executeshell
On Wednesday, 29 April 2015 at 21:56:18 UTC, Ali Çehreli wrote: Certainly not. The output is an object of a special type, which the documentation refers to as 'auto'. Grrr... :) Ok, maybe it's a Voldemort type. Anyway... That's idiotic, to be frank, it should just be a traditional struct declared outside. "Just because we can do a thing, it does not necessarily follow that we must do that thing" -- from the Gospel of Kirk
getopt helpWanted
Hello. Help me please to understand, how to show usage help to user, who enter wrong options? For example, user not provided required filename. I want to show error message, and program usage help text. But likely getopt don't provide help text until valid options will be parsed. Reduced code: /// import std.stdio: writefln; import std.getopt; void main (string[] args) { string fname; GetoptResult helpInfo; try { helpInfo = getopt( args, std.getopt.config.required, "file|f", "File name", &fname); writefln("Options parsed: fname=%s", fname); } catch(Exception e) { writefln("\nERROR: %s", e.msg); defaultGetoptPrinter("Program usage:", helpInfo.options); } } /// Output: ERROR: Required option file|fwas not supplied Program usage:
Re: getopt helpWanted
What you're trying to do is currently impossible. I filed a bug (https://issues.dlang.org/show_bug.cgi?id=14525) because what you're trying to do really should be possible. import std.stdio : writefln; import std.getopt; void main(string[] args) { string fname; try { getopt(args, std.getopt.config.required, "file|f", "File name", &fname); writefln("Options parsed: fname=%s", fname); } catch (GetOptException e) { writefln("\nERROR: %s", e.msg); auto p = ["placeholder"]; auto r = getopt(p, "file|f", "File name", &fname); defaultGetoptPrinter("Program usage:", r.options); } }
Re: Create custom data types
On Wednesday, 29 April 2015 at 21:49:08 UTC, Ali Çehreli wrote: On 04/29/2015 12:53 PM, Dennis Ritchie wrote: On Wednesday, 29 April 2015 at 17:52:27 UTC, Ali Çehreli wrote: It should be easy to make a template of it. (I really think it should already be in Phobos. :) ) Where can I find documentation on this subject? Once a piece of code works for a particular type or value, it is easy to convert it to a template by moving the type and the value to the template parameter list and replace all occurrences of those with template parameters: - int -> T - -32_000 -> minValue - 32_000 -> maxValue Here it is: import std.exception; struct CustomInteger(T, T minValue, T maxValue) { T value_; alias value this; @property T value() const { enforce((value_ >= minValue) && (value_ <= maxValue)); return value_; } @property void value(T v) { value_ = v; } } unittest { alias Balance = CustomInteger!(int, -32_000, 32_000); auto b = Balance(42); assert(b == 42); b = 40_000; void foo(int) {} assertThrown(foo(b)); } void main() {} Ali Thanks. And how can I stop all attempts to perform actions arifmiticheskih the type int? Ie action to "t += b;" suppressed to compile. - import std.exception, std.stdio; struct CustomInteger(T, T minValue, T maxValue) { T value_; alias value this; @property T value() const { enforce((value_ >= minValue) && (value_ <= maxValue)); return value_; } @property void value(T v) { value_ = v; } } void main() { alias Balance = CustomInteger!(int, -32_000, 32_000); auto b = Balance(42); // b += 5; // Error: 'b += 5' is not a scalar, // it is a CustomInteger!(int, -32000, 32000) int t = 4; t += b; // OK writeln(b); // prints 46 }
Re: Create a case-insensitive startsWith
if("0X".std.string.indexOf("0x", CaseSensitive.no) == 0) should work
Re: Create custom data types
On 04/29/2015 03:48 PM, Dennis Ritchie wrote: Thanks. And how can I stop all attempts to perform actions arifmiticheskih the type int? Ie action to "t += b;" suppressed to compile. Some operator overloading is needed. I am pretty sure someone must have implemented such a type. What I add below probably addresses just what you ask. I would like to see others chime in with their solutions or potentially the solutions that are already in Phobos. Continued inline... - import std.exception, std.stdio; struct CustomInteger(T, T minValue, T maxValue) { T value_; alias value this; @property T value() const { enforce((value_ >= minValue) && (value_ <= maxValue)); return value_; } @property void value(T v) { value_ = v; } Add this: ref CustomInteger opOpAssign(string op, T2)(T2 rhs) { static if (is (T2 == CustomInteger)) { mixin("value_ " ~ op ~ "= rhs.value_;"); return this; } else { return this.opOpAssign!(op, CustomInteger)(CustomInteger(rhs)); } } } void main() { alias Balance = CustomInteger!(int, -32_000, 32_000); auto b = Balance(42); // b += 5; // Error: 'b += 5' is not a scalar, // it is a CustomInteger!(int, -32000, 32000) Now this works: b += 5; assert(b == 47); b += b; assert(b == 94); int t = 4; t += b; // OK writeln(b); // prints 46 } Ali
Re: Create custom data types
On 04/29/2015 04:16 PM, Ali Çehreli wrote: ref CustomInteger opOpAssign(string op, T2)(T2 rhs) { static if (is (T2 == CustomInteger)) { mixin("value_ " ~ op ~ "= rhs.value_;"); return this; } else { return this.opOpAssign!(op, CustomInteger)(CustomInteger(rhs)); Playing a little more, the following shorter equivalent of the last line works as well: return opOpAssign!op(CustomInteger(rhs)); Ali
Re: Create custom data types
On Wednesday, 29 April 2015 at 23:22:43 UTC, Ali Çehreli wrote: On 04/29/2015 04:16 PM, Ali Çehreli wrote: ref CustomInteger opOpAssign(string op, T2)(T2 rhs) { static if (is (T2 == CustomInteger)) { mixin("value_ " ~ op ~ "= rhs.value_;"); return this; } else { return this.opOpAssign!(op, CustomInteger)(CustomInteger(rhs)); Playing a little more, the following shorter equivalent of the last line works as well: return opOpAssign!op(CustomInteger(rhs)); Ali How do I disable it? I need to prohibit all operations to the type int. - auto b = Balance(42); int t = 4; t += b; // error in compile time
Re: ldc std.getopt
On Wednesday, 29 April 2015 at 20:45:26 UTC, Anon wrote: On Wednesday, 29 April 2015 at 19:43:44 UTC, Laeeth Isharc wrote: I get the following errors under LDC (this is LDC beta, but same problem under master) although the code compiles fine under DMD. Am I doing something wrong? The help generating feature of std.getopt is new in 2.067. Use branch "merge-2.067" for that. Otherwise, don't use std.getopt's help generation just yet. Thanks! Laeeth.
Re: String from executeshell
On Wednesday, 29 April 2015 at 21:56:18 UTC, Ali Çehreli wrote: On 04/29/2015 02:54 PM, Ali Çehreli wrote: executeShell returns the status and the output as a type Certainly not. The output is an object of a special type, which the documentation refers to as 'auto'. Grrr... :) Ok, maybe it's a Voldemort type. Anyway... The function's documentation has a "Returns" section, which says: Returns: An std.typecons.Tuple!(int, "status", string, "output").
dub building is extremely slow
dub build is running on centos7. It works well until today, It becomes very slow suddenly. It will take minuties per compilation, there is 10 files in project. Has anyone experienced this?
Re: dub building is extremely slow
On Thursday, 30 April 2015 at 02:02:50 UTC, zhmt wrote: dub build is running on centos7. It works well until today, It becomes very slow suddenly. It will take minuties per compilation, there is 10 files in project. Has anyone experienced this? It is because: The dub will connect to some website to check version of packages,but the destination website is limited by my gov,so... the compilation is slowed. solution: shutdown the network of pc.
Re: shouldn't this code at least trigger a warning?
On 4/29/15 5:25 AM, "Marc =?UTF-8?B?U2Now7x0eiI=?= " wrote: On Wednesday, 29 April 2015 at 06:37:44 UTC, ketmar wrote: subj. the code: void main () { import std.stdio; char ch = '!'; switch (ch) { int n = 42; case '!': writeln(n, ": wow!"); break; default: } } i think that such abomination should: 1. be forbidden, or 2. trigger a warning, or 3. execute initializer anyway. currently the code is allowed, no warnings triggered, yet `n` is uninitialized. and having uninitialized variable without "=void" "should not be". Agreed, this should be an error. Variables declared in one case block aren't even visible in other case blocks, this was probably an oversight. I thought they were? A switch scope is just like a normal scope, but with a bunch of labels. They should be visible in all *trailing* case blocks, since the rule is that your code that uses it must come after the declaration. I agree the above should not be allowed. It's clear the compiler can detect a situation where n is used but not initialized. -Steve
Re: Fuzzy Levenshtein variant of std.conv.to
On Wednesday, 29 April 2015 at 14:46:04 UTC, Per Nordlöw wrote: On Tuesday, 28 April 2015 at 23:09:27 UTC, Per Nordlöw wrote: On Tuesday, 28 April 2015 at 16:20:24 UTC, Per Nordlöw wrote: I update my Github repo. I had forgotten to push my latest changes. I solved it. I started working on this yesterday before you solved it, and ended up finishing a solution. It was a fun excercise, thanks. https://gist.github.com/JakobOvrum/515737710619a9d97273 It uses a loop instead of a range composition because of the early return when the Levenshtein distance is 0; that would be clumsy to express with ranges.
Re: Create custom data types
On 04/29/2015 04:30 PM, Dennis Ritchie wrote: > On Wednesday, 29 April 2015 at 23:22:43 UTC, Ali Çehreli wrote: >> On 04/29/2015 04:16 PM, Ali Çehreli wrote: >> >>> ref CustomInteger opOpAssign(string op, T2)(T2 rhs) >>> { >>> static if (is (T2 == CustomInteger)) { >>> mixin("value_ " ~ op ~ "= rhs.value_;"); >>> return this; >>> >>> } else { >>> return this.opOpAssign!(op, >>> CustomInteger)(CustomInteger(rhs)); >> >> Playing a little more, the following shorter equivalent of the last >> line works as well: >> >> return opOpAssign!op(CustomInteger(rhs)); >> >> Ali > > How do I disable it? I think I don't understand the requirements here probably because I don't know Ada and I don't have time to even think about such a type. Sorry. :-/ > I need to prohibit all operations to the type int. > > - > auto b = Balance(42); > > int t = 4; > > t += b; // error in compile time That works because of 'alias this'. I would remove that line and start adding more and more operator overloads as needed. Ali
Re: getopt helpWanted
Thank you, Brian!