Re: Templates for DRY code
On Saturday, 6 January 2018 at 23:32:42 UTC, Paul Backus wrote: On Saturday, 6 January 2018 at 03:38:35 UTC, codephantom wrote: or even.. a.append( s.to!ConvertToElementType(a) ); That's not valid code of course, but the semantics are all contained in that single chunk. This works: import std.range.primitives: ElementType; a ~= s.to!(ElementType!(typeof(a))); I guess this brings us back to Ali's point about finding the balance between being explicit and fully automatic. I certainly prefer: a.append(s); vs a ~= s.to!(ElementType!(typeof(a))); // this hurts by brain ;-) The only problem with the Ali's suggestion of using append, is we always bring background knowledge everytime we read and write code, and, we all know that you cannot append a string to an array of doubles (that is our background knowledge). I guess if we knew that you can do that now, then 'a.append(s);' would be just fine. But I'm not a big fan of 'implicit' conversions in type safe languages, even when those conversion are type safe. So there's yet another balance to get right.
Re: Templates for DRY code
On Saturday, 6 January 2018 at 03:08:19 UTC, Ali Çehreli wrote: I agree with your point as well. A better name can help there a little. void ConvertAndAppend(T, S)(ref T[] arr, S s) { arr ~= s.to!T; } problem solved ;-) btw. I never thought that I would be able (or actually..willing) to program using templates, still I found D. Thanks to those responsible for making them so easy to use (presumably Walter and Andrei).
Re: Templates for DRY code
On Saturday, 6 January 2018 at 03:08:19 UTC, Ali Çehreli wrote: It's hard to find a balance between fully explicit and fully automatic. I find myself going back and forth between those two extremes. Ali Code is something that humans write and read (and read far more than write). So I prefer to optimise for mental processing ;-) By this, I mean reducing the amount of information I need to chunk, to make sense of something (whether that be writing, or reading). e.g double[] a; string s = "1.2"; a.append(s) requires me to go off and discover what append is doing, since 'append' is clearly not correctly describing what is actually going on here, in this little chunk. So, now I have to go off and discover the extra chunk I need, in order to make sense of this little chunk. Suddenly, the chunk has become a lot larger than it needed to be. so yeah, a simple rename of append would help.. or even.. a.append( s.to!ConvertToElementType(a) ); That's not valid code of course, but the semantics are all contained in that single chunk.
Re: Templates for DRY code
On Saturday, 6 January 2018 at 01:33:11 UTC, Ali Çehreli wrote: One solution is to wrap ~= in a function template. Now the conversion is automatically made to the element type of the array: ... . I think append() could be a part of std.array but I can't find anything like that in Phobos. Ali The problem with this, in my opinion, is that your template 'append' is doing a conversion behind the scenes..ie. I wouldn't know that 'append' actually means 'convert & then append'. When I read: double[] a; string s = "1.2"; a.append(s); I think to myself...wtf is going on here? How can you append a string to an array of doubles? That's when I'd have go and find the append template and work out what it is really doing.
Re: Slices and Dynamic Arrays
On Sunday, 31 December 2017 at 03:57:17 UTC, Tony wrote: On Sunday, 31 December 2017 at 03:08:05 UTC, Ivan Trombley wrote: double[] D = [3.14159]; Can you guess what D is? :D It took me a while but I finally came up with "a slice of pi" a slice of pi is irrational.
Re: Finding unsafe line of code
On Friday, 29 December 2017 at 09:38:50 UTC, Vino wrote: Let me re-frame the question with an example, as the Dsafe the below line of code is considered as unsafe(Pointer arithmetic), so let imagine that we have several similar line of code, how do we find such unsafe line, does the compiler check these unsafe code and complain while compiling a .d program or do we need to pass any compiler arguments to perform these check while compiling the code or do we need to manually perform an analysis of each line of code and correct the same in case if we find any unsafe code. ini[10] a; int* p = &a[0]; for (size_t i=0; i <= 10; i++) p[i] = ...; From, Vino.B Is this what you're looking for? https://dlang.org/spec/function.html#safe-functions Just annotate your functions with @safe (as @system is the default).
Re: Finding unsafe line of code
On Friday, 29 December 2017 at 08:21:10 UTC, Vino wrote: Hi All, Is there a way to find or test which line of a give code is not safe(possible memory corruption). From, Vino.B That question needs to be refined ;-)
Re: No of threads
On Wednesday, 20 December 2017 at 13:41:06 UTC, Vino wrote: Hi Ali, Thank you very much, below are the observations, our program is used to calculate the size of the folders, and we don't see any improvements in the execution speed from the below test, are we missing something. Basically we expected the total execution time for the test 2 , as the time taken to calculate the size of the biggest folder + few additional mins, the biggest folder size is of 604 GB. Memory usage is just 12 MB, whereas the server has 65 GB and hardly 30% - 40% is used at any given point in time, so there is no memory constrain. Are you running this over the network, or on (each) server that contains the actual folders?
Re: DateTime formatting
On Wednesday, 20 December 2017 at 14:30:55 UTC, bauss wrote: I can't seem to find anything in Phobos that allows you to specify custom formats for dates. sometimes it's just better to take control of things yourself ;-) https://forum.dlang.org/post/dmxdtciktpggcxybd...@forum.dlang.org
tuples from text file
so I have a text file containing 3 lines(e.g): 5, "hello", 4.3 "hello", 4.3 "hello", "world", 1, 2, 3, 5.5 Now I want to create tuples from each line. However, (using line 1 as example), I get: Tuple!string("5, \"hello\", 4.3") but I really want: Tuple!(int, string, double)(5, "hello", 4.3) I know why - because a line is a string. But anyone got an idea on how to extract the string into separate elements that can be correctly 'tuple'd" according to the type of each element? // --- module test; import std.stdio : writeln; import std.typecons; import std.string; import std.file : readText; void main() { string myFile= "tuples.txt"; // contains 3 lines as per examples above auto lineArr = readText(myFile).splitLines(); writeln( tuple(lineArr[0]) ); // doesn't give me the tuple I want. } //---
Re: No of threads
On Tuesday, 19 December 2017 at 10:24:47 UTC, Vino wrote: foreach (d; taskPool.parallel(xxx,20)) : As in Windows 2008 whatever value is set for the parallel the total number of threads does not increase more than 12. So not sure if this is correct, so can any one explain me on same. something to do with your cacheLineSize perhaps?
Re: Alias example should supposedly be illegal, but runs fine
On Tuesday, 19 December 2017 at 01:30:07 UTC, Mike Franklin wrote: writeln(S.j); // Error: Instance symbols cannot be used through types. I don't understand why you would say that is a bug. i.e. // import std.stdio; struct S { int j; } void main() { writeln(typeof(S.j).stringof); // prints: int } // - "AliasDeclarations create a symbol that is an alias for another type, and can be used anywhere that other type may appear. ". Since typeof S.j is an int, that seems consistent with this requirement, that alias is an alias for another type.
Re: Alias example should supposedly be illegal, but runs fine
On Monday, 18 December 2017 at 23:44:46 UTC, Michael wrote: alias a = s.i; // illegal, s.i is an expression Actually, as I understand it, the example provided in 10. is legal (because it aliases a type), and the example provided in 3. is illegal (because it aliases an expression) perhaps the examples in 10 and 3 should be swapped. https://dlang.org/spec/declaration.html#alias
Re: Alias example should supposedly be illegal, but runs fine
On Monday, 18 December 2017 at 23:44:46 UTC, Michael wrote: alias a = s.i; // illegal, s.i is an expression alias a = s.i; (this is an alias to a type, since s.i is an int) Hence it is actually 'legal', as far as I understand. i.e... "AliasDeclarations create a symbol that is an alias for another type, and can be used anywhere that other type may appear. " What is 'illegal', is an alias to an expression.. for example: alias strlen = string.sizeof;
Re: Array Template
On Saturday, 16 December 2017 at 14:14:28 UTC, Vino wrote: Yes, will give a try. From, Vino.B well, this sort of gets there ;-) // - module test; import std.stdio; import std.variant; import std.typecons; import std.conv; import std.string; void main() { Variant[] arr; auto x = tuple(5, "hello", 4.3); arr ~= cast(Variant)x; auto y = tuple("hello", 4.3); arr ~= cast(Variant)y; auto z = tuple("hello", "world", 1, 2, 3, 5.5); arr ~= cast(Variant)z; int i = 0; foreach(elem; arr) { writeln( "arr[", i, "] values are : ", to!(string)((to!(string)(elem)) [( indexOf( to!(string)(elem), ")" ) + 2)..($-1)]) ); i++; } } // -
Re: Where is sleep()?
On Sunday, 17 December 2017 at 08:32:20 UTC, Ryan David Sheasby wrote: Hey guys. First time poster here. I've searched high and low but can't seem to find a simple sleep/delay/wait/pause function in the core or in phobos. The most recent information I can find about it is this forum post from 12 years ago: http://forum.dlang.org/thread/avr99b$b8j$2...@digitaldaemon.com In which they suggest using std.c.time which is now depreciated and seems to have been replaced by core.stdc.time which doesn't have any sleep functions... What am I missing? // -- import std.stdio; import core.thread; void main() { int waitTime = 5; writeln("Waiting ", waitTime, " seconds..."); Thread.sleep(waitTime.seconds); writeln("Done waiting!"); } // --
Re: Scope failure is not preventing application crush in case of uncaught exceptions
On Sunday, 17 December 2017 at 08:26:03 UTC, Jonathan M Davis wrote: assert(0) does indeed turn into a HLT instruction in -release mode (as does any assertion that's known to be false at compile time). It's a special case intended for marking code that's supposed to be unreachable. Without -release, failed assertions throw AssertErrors, so they're Errors not Exceptions, though I think that scope statements currently catch and then rethrow Throwable rather than Exception, which is why AssertErrors would be affected. - Jonathan M Davis It's a little confusing, because Andrei's book says that scope(failure) guarantees statement will be executed, if and only if the current scope is exited by throwing an 'exception'. One could *mistakingly* take that as meaning, throwing an object rooted in the 'Exception' subclass of Throwable. Of course assert actually throws an exception too, but it's a special kind of exception rooted in the 'Error' subclass of Throwable. Perhaps, to be clearer, Andrei's book should have said: scope(failure) guarantees statement will be executed, if and only if the current scope is exited by throwing an object that inherits from type Throwable. That would include, objects rooted in the 'Exception' subclass, as well as objects rooted in 'Error' subclass. In which case, there's no bug in that code. It's doing what it's meant to be doing.
Re: Scope failure is not preventing application crush in case of uncaught exceptions
On Sunday, 17 December 2017 at 00:10:27 UTC, Anonymouse wrote: If you return inside a scopeguard though, the exception (or error!) is swallowed. https://run.dlang.io/is/GEtQ6D The scope guard will not 'swallow' it, if you use -release mode. Which suggests to me, that assert(0) operates differently when 'not' using -release mode. My 'guess' is, that release mode issues a halt instruction, whereas in non-release mode it is just an exception like any other exception.
Re: Array Template
On Friday, 15 December 2017 at 17:21:55 UTC, Vino wrote: Hi All, Request your help, Is it possible to an template array something similar as below so that we can insert any type of value(string, int etc). If possible can you provide me a example of how to define such array. Array!(Tuple!(T n)) From, Vino.B Do you mean 'an array of variable types of tuples'. If so...good luck with that ;-)
Re: How to catch line number of exception without catching it ?
On Wednesday, 13 December 2017 at 18:24:09 UTC, Thomas wrote: Or is there a better solution for tracing the error position from root till the branch ? Speaking of tracing exceptions, here's my favourite one .. so far ;-) (I mean come on.. debugging is great fun!) btw. If you compile/run this code on Windows, using LDC, you'll get a nice little beep from the speaker (when it runs). // module test; import std.stdio; void main() { auto str = "hello"; string * ptr = &str; writeln(ptr[1]); //compile without using the -O option // writeln(ptr.ptr[1]); // the above line was meant to be this line. } //
Re: Date Formating
On Wednesday, 13 December 2017 at 07:35:40 UTC, Jonathan M Davis wrote: In general, you probably want to cast the SysTime to a DateTime if you're going to do something like that. yes, I would agree ;-) Of course the intention was not really to just format it the same way as Clock.currTime() does it, but rather to provide a way to more easily customise the format, however one likes, whenever one likes.. e.g.the following small change to the format string would make it return: 20171213_1924_41 (that's more like something I'd use) return format("%04s%02s%02s_%02s%02s_%02s", (d.year), to!(int)(d.month), (d.day), (d.hour), (d.minute), (d.second) );
Re: Understanding how dub works
On Tuesday, 12 December 2017 at 22:20:41 UTC, datboi wrote: Hi, I'm learning D (obliviously) learning D in an oblivious manner can be difficult ;-)
Re: Date Formating
On Tuesday, 12 December 2017 at 15:56:59 UTC, Vino wrote: Hi All, Request out help on date formatting, I have code which output the date and time as below , i we need it without the last few numbers.,ie "-MMM-DD HH:MM:SI" Output : 2017-Sep-06 16:06:42.7223837 Required Output : 2017-Sep-06 16:06:42 From, Vino.B just playing with this... // -- module test; void main() { import std.stdio; writeln( GetFmtDate() ); // e.g: 2017-Dec-13 13:30:23 } string GetFmtDate() { import std.datetime; import std.ascii : toUpper; import std.conv : to; import std.string : format; auto d = Clock.currTime(); string fmtMonth = toUpper(to!string(d.month)[0]) ~ to!string(d.month)[1..$]; return format("%04s-%s-%02s %02s:%02s:%02s", (d.year), fmtMonth, (d.day), (d.hour), (d.minute), (d.second) ); } // --
Re: Why is there no std.stream anymore?
On Tuesday, 12 December 2017 at 02:15:13 UTC, codephantom wrote: just playing around with this also...in case you only want to read n bytes.. // --- module test; import std.stdio, std.file, std.exception; import std.datetime.stopwatch; void main() { string filename = "test.txt"; // a text file //string filename = "test.exe"; // a binary file enforce(filename.exists, "Umm..that file does not exist!"); auto file = File(filename, "r"); ubyte[] buf; import std.datetime : MonoTime; auto t2 = MonoTime.currTime; // just read the first n bytes. int bytesToRead = 4; // change this n int bufCount; while ( !file.eof() && bufCount < bytesToRead ) { buf = file.rawRead(new ubyte[1]); if(!file.eof()) { process(cast(char)(buf[0])); bufCount++; } } writeln("-"); writeln("this took : ", MonoTime.currTime - t2); writeln("-"); writeln(); return; } void process(char someChar) { import std.ascii : isPrintable; if( isPrintable(someChar) ) writeln("found a printable character: ", someChar); else writeln("found a non printable character"); } // ---
Re: Why is there no std.stream anymore?
On Monday, 11 December 2017 at 20:51:41 UTC, Jordi Gutiérrez Hermoso wrote: I'd like to read from a file, one byte at a time, without loading the whole file in memory. just playing around with this // module test; import std.stdio, std.file, std.exception; void main() { string filename = "test.txt"; enforce(filename.exists, "Umm..that file does not exist!"); auto file = File(filename, "r"); char[] charBuf; while (!file.eof()) { charBuf = file.rawRead(new char[1]); if(!file.eof()) process(cast(char)(charBuf[0])); } return; } void process(char someChar) { import std.ascii : isPrintable; if( isPrintable(someChar) ) writeln("found a printable character: ", someChar); else writeln("found a non printable character"); } //
Re: Sort in return statement
On Saturday, 9 December 2017 at 14:49:28 UTC, Seb wrote: randomSample doesn't sort its returned range Not by design, however, because it samples in the order that the elements appear, *if* those elements are already sorted (whether by design or explicately sorted), then the results of the randomsample are also implicitly already sorted ;-)
Re: Sort in return statement
On Saturday, 9 December 2017 at 14:18:00 UTC, Seb wrote: Yeah, you are very welcome. It's a bit hidden in the docs: Yes. Thanks for that. After lots of reading, and testing, I managed to get a simple, one liner ;-) (doesn't seem like .release is needed though.) // --- auto draw8Numbers() { import std.meta : aliasSeqOf; import std.range : iota; import std.random : randomSample; return randomSample([ aliasSeqOf!(iota(1,46)) ], 8); } // ---
Re: Sort in return statement
On Saturday, 9 December 2017 at 04:31:33 UTC, SimonN wrote: Yes, this works, and your algorithm would even accept arbitary random-access ranges, not merely arrays. Would be nice if I could do it all as a 'one liner': // int[] draw8Numbers() { import std.algorithm.sorting : sort; import std.random : randomShuffle; import std.meta : aliasSeqOf; import std.range : iota; import std.range : take; import std.array : array; // return a sorted array of 8 random numbers, between 1..45 inclusive. return sort(randomShuffle([ aliasSeqOf!(iota(1,46)) ]).take(8)).array; } // ---
Re: Sort in return statement
On Saturday, 9 December 2017 at 02:45:35 UTC, rjframe wrote: `sort` returns a SortedRange of ushorts, not an array of ushorts. Make it: ``` import std.array : array; return sort(numbers.take(8)).array; ``` --Ryan That's it! Thanks Ryan.
Re: Check whether a file is empty.
On Friday, 8 December 2017 at 19:13:20 UTC, vino wrote: Hi, The code is same just copy pasted the code form Windows 7 into Windows 2003 and executed, in Windows 7 the log file is of size 0 where as in windows 2003 the log file is of size 2 byte where the log file in both the server is empty. From, Vino.B It certainly sounds like some kind of encoding issue. I guess you don't have much choice other than to read the contents of the file, and determine what it actually contains. Assuming these log files of yours are 'ascii text' files, then if the file is less than say .. 5 bytes.. you could check if it *only* contained *non-printable* characters, in which case it's 'likely' an empty file. something very silly, like this, might do it ;-) // --- bool isFileLikelyEmpty(string filename) { import std.exception, std.file, std.ascii, std.conv; File f = filename; enforce(f.size < 5, "This file is not likely to be empty." ~ " No point in continuing."); // 5 seems reasonable cutoff ;-) bool result = false; int charCount = 0; auto str = readText(filename); foreach(c; str) { // https://dlang.org/phobos/std_ascii.html#isPrintable if( !isPrintable(c) ) charCount++; } if(charCount == str.length) result = true; // file is likely empty, as all characters are non-printable. return result; } // -
Sort in return statement
Anyone got ideas on how to get sort() working in the *return* statement? // ushort[] draw8Numbers() { import std.meta : aliasSeqOf; import std.range : iota; ushort[] numbers = [ aliasSeqOf!(iota(1,46)) ]; import std.random : randomShuffle; randomShuffle(numbers); import std.range : take; import std.algorithm.sorting : sort; return numbers.take(8); /* ok */ //return sort(numbers.take(8)); /* I want this, but it won't work. */ } // -
Re: Optimizing a bigint fibonacci
On Wednesday, 6 December 2017 at 09:59:12 UTC, codephantom wrote: On Wednesday, 6 December 2017 at 09:12:08 UTC, helxi wrote: This is question not directly related to language concepts, it's got more to do with the application. I would appreciate if anyone would point to me how I could optimize this bit of code Compile it with ldc ;-) also, fyiin my test, when compiling with dmd and using -m32 (instead of -m64) it timed *twice as fast* compared to the timing of the 64bit run; whereas compiling with ldc, both the 32bit and 64bit run timed at about the same speed. lesson? don't 'just' look at how to optimise your 'code' ;-)
Re: Optimizing a bigint fibonacci
On Wednesday, 6 December 2017 at 09:12:08 UTC, helxi wrote: This is question not directly related to language concepts, it's got more to do with the application. I would appreciate if anyone would point to me how I could optimize this bit of code Compile it with ldc ;-)
Re: lower case only first letter of word
On Tuesday, 5 December 2017 at 13:31:17 UTC, Marc wrote: Does D have a native function to capitalize only the first letter of the word? (I'm asking that so I might avoid reinvent the wheel, which I did sometimes in D) // module test; import std.stdio; void main() { string myString = "heLlo WoRlD!"; writeln( HereItIs(myString) ); } string HereItIs(string someString) { import std.uni : toLower; import std.ascii : toUpper; return (someString.ptr[0].toUpper ~ someString[1..$].toLower); } // --
Re: Passing Function as an argument to another Function
On Monday, 4 December 2017 at 11:30:02 UTC, codephantom wrote: On Monday, 4 December 2017 at 11:05:22 UTC, Vino wrote: The original program is as below Error: FunTest.d(52): Error: template FunTest.ptProcessFiles cannot deduce function from argument types !()(string, Array!(Tuple!(string, string)) function(string FFs, string Step, int DirAged), File, File, string, int), //auto CleanDirlst = "C:\\Temp\\BACKUP, C:\\Temp\\EXPORT"; Array!string CleanDirlst = ["C:\\Temp\\BACKUP, C:\\Temp\\EXPORT"]; grrr... //auto CleanDirlst = "C:\\Temp\\BACKUP, C:\\Temp\\EXPORT"; Array!string CleanDirlst = ["C:\\Temp\\BACKUP", "C:\\Temp\\EXPORT"];
Re: Passing Function as an argument to another Function
On Monday, 4 December 2017 at 11:05:22 UTC, Vino wrote: The original program is as below Error: FunTest.d(52): Error: template FunTest.ptProcessFiles cannot deduce function from argument types !()(string, Array!(Tuple!(string, string)) function(string FFs, string Step, int DirAged), File, File, string, int), //auto CleanDirlst = "C:\\Temp\\BACKUP, C:\\Temp\\EXPORT"; Array!string CleanDirlst = ["C:\\Temp\\BACKUP, C:\\Temp\\EXPORT"];
Re: Windows Share Path
On Saturday, 2 December 2017 at 14:23:48 UTC, Vino wrote: Hi, Even tried the Option "Run with Highest Privilege" but no luck. and also tried with option "Configure for : Windows Vista , Windows Server 2008" From, Vino.B You haven't accidently ticked the 'Do not store password' option? That is a common mistake. (i.e. make sure it's *not* ticked, and reinsert credentials). In my 'sysadmin' days, I *refused* to use the windows scheduler. I didn't want something that kept changing depending on which version of windows you were using. I wanted consistency. From memory, i think I installed 'system scheduler' on all my MS servers. https://www.splinterware.com/tour/scheduler.html
Re: Windows Share Path
On Saturday, 2 December 2017 at 07:48:14 UTC, Vino wrote: Even tried with the below code, it works manually but not via Windows scheduler with option "Run whether user is logged on or not" Are you using appropriate credentials in the scheduled task?
Re: scope(exit) and Ctrl-C
On Saturday, 2 December 2017 at 04:28:57 UTC, Wanderer wrote: Thanks! This works. But it seems a little bit suspicions that D's type for handler function has `nothrow` `@nogc` and `@system`. I wonder why is that? During execution of that handler, it make sense to prohibit the allocation of any GC memory, and prohibit the throwing of any exceptions. I presume that's why they're there (??) @system is default (btw, change -1 to 1 in the exit function, i.e. -1 is not valid, 0..255 is valid.. but some of those you should avoid using).
Re: scope(exit) and Ctrl-C
On Saturday, 2 December 2017 at 00:41:19 UTC, Wanderer wrote: Is there any method to cleanup on Ctrl-C? // -- import std.stdio; import core.thread; extern(C) void signal(int sig, void function(int)); extern(C) void exit(int exit_val); extern(C) void handle(int sig) { writeln("Control-C was pressed..aborting programgoodbye..."); // do more stuff? exit(-1); } void main() { enum SIGINT = 2; signal(SIGINT,&handle); scope (exit){ writeln("Cleanup"); } writeln("Waiting..."); Thread.sleep(10.seconds); writeln("Done waiting..."); } // -
Re: Floating point types default to NaN?
On Friday, 24 November 2017 at 14:30:44 UTC, A Guy With a Question wrote: I would have expected 0 to be the default value. What's the logic behind having them being NaN by default? https://dlang.org/spec/type.html http://www.drdobbs.com/cpp/nans-just-dont-get-no-respect/240005723
Re: Changing the class data underneath some reference
On Thursday, 30 November 2017 at 00:52:25 UTC, codephantom wrote: ... sorry, don't know how the int * got in there ;-) Anyway..who said you can't use pointers in D? Just change: //SomeType bar = foo; SomeType * bar = &foo;
Re: Changing the class data underneath some reference
On Thursday, 30 November 2017 at 00:40:51 UTC, David Colson wrote: Hello all! I'm getting settled into D and I came into a problem. A code sample shows it best: class SomeType { string text; this(string input) {text = input;} } void main() { SomeType foo = new SomeType("Hello"); SomeType bar = foo; foo = new SomeType("World"); writeln(bar.text); // Prints hello // I'd like it to print World } In the C++ world I could do this using pointers and changing the data underneath a given pointer, but I can't use pointers in D, so I'm not sure how I can get this behaviour? I'd be open to other ways of achieving the same affect in D, using more D like methods. void main() { SomeType foo = new SomeType("Hello"); int * ptr; SomeType * bar; bar = &foo; foo = new SomeType("World"); writeln(bar.text); // Prints World }
Re: Email validation
On Tuesday, 28 November 2017 at 18:47:06 UTC, Vino wrote: Hi All, Can you please provide me some example on who to validate an email address as the document dose not have an example for the same Ex: vino.bhee...@hotmail.com Conditions : The domain should contain only "hotmail.com" The email address should contain the symbol "@" From, Vino.B Here's another nice option I just found. Interestingly, I had to disable Avast antivirus, otherwise when I compile it, Avast thinks the exectuable is 'suspicous' and prevents any further access to it...wtf? // - module test; import std.stdio; import std.algorithm; /+ CONDITIONS: - The domain should contain only "hotmail.com" - The email address should contain the symbol "@" +/ void main() { string domainRequired = "@hotmail.com"; string emailAddress = "vino.bhee...@hotmail.com"; emailAddress.endsWith(domainRequired) ? writeln("domain ok") : writeln("invalid domain"); } //
Re: Email validation
On Tuesday, 28 November 2017 at 22:42:27 UTC, Mike Wey wrote: isMail only checks the formatting of the email address and optionally if the domain has a MX record. I don't believe MX validation (checkDns) is implemented yet.
Re: Email validation
On Tuesday, 28 November 2017 at 18:47:06 UTC, Vino wrote: Hi All, Can you please provide me some example on who to validate an email address as the document dose not have an example for the same Ex: vino.bhee...@hotmail.com Conditions : The domain should contain only "hotmail.com" The email address should contain the symbol "@" From, Vino.B test/improve it yourself. but you get the idea // -- module test; import std.stdio; import std.algorithm; /+ CONDITIONS: - The domain should contain only "hotmail.com" - The email address should contain the symbol "@" +/ void main() { string domainRequired = "hotmail.com"; string emailAddress = "vino.bhee...@hotmail.com"; auto checkDomain = findSplitAfter(emailAddress, "@"); // requires import std.algorithm //writeln(checkDomain); // Tuple!(string, string)("vino.bheeman@", "hotmail.com") if (checkDomain[1] == domainRequired) writeln("domain ok"); else writeln("invalid domain"); } // --
Re: Email validation
On Tuesday, 28 November 2017 at 19:32:40 UTC, Vino wrote: Can you provide me a example, as the link does not have any examples. From, Vino.B btw... yes documentation is an acknowledged issue with regards to phobos...but..that aside...it can also be useful (and wise) to look at the unit tests in the source code. I'm not sure that simply calling something you don't know anything about is such a good idea these days ;-) ...fortunately, we have access to the source - which gets installed with dmd. or you can find it on github. https://github.com/dlang/phobos
Re: Is variable void?
On Tuesday, 28 November 2017 at 05:10:39 UTC, bauss wrote: null != void also...void is a completely useless concept for initialisation. what can you determine about the nothingness of void? ... nothing. writeln(typeof(void).stringof); // ?? what do I know now? nothing. vs Nullable!int x; writeln(typeof(x).stringof); // Nullable!int .. now I know something.
Re: Is variable void?
On Tuesday, 28 November 2017 at 05:10:39 UTC, bauss wrote: null != void "initialized or not?" != void
Re: Is variable void?
On Saturday, 25 November 2017 at 15:34:21 UTC, John Chapman wrote: Is there any way of determining whether a variable has been initialized or not? For example, if something is declared like this: int x = void; can I check if it's void before I use it, say, in a function it's been passed to? // -- module test; import std.stdio; import std.typecons; // see: https://dlang.org/phobos/std_typecons.html#Nullable void main() { Nullable!int x; // requires: import std.typecons assert(x.isNull); writeln("x is ", x); x = 1; assert(!x.isNull); writeln("x is ", x); x.nullify(); // Forces x back to a null state. assert(x.isNull); writeln("x is ", x); } // --
Re: betterC and noboundscheck
On Friday, 24 November 2017 at 05:01:17 UTC, Basile B. wrote: On Friday, 24 November 2017 at 00:17:31 UTC, codephantom wrote: On Wednesday, 22 November 2017 at 15:10:40 UTC, Oleg B wrote: If I add -noboundscheck flag all works fine. dmd version is 2.076.1 Why -betterC flag not 'include' -noboundscheck flag? It's bug or in some cases it's useful? Interestingly, ldc2 will compile this ok, without the -noboundscheck flag btw. you should start using: boundscheck=off/on/safeonly flag instead i believe. https://dlang.org/dmd-windows.html#switch-boundscheck It's b/c LDC2 doesn't have the most recent betterC features. It works just like it worked in older DMD release (e.g w 2.075), when betterC was "inexact" / "mostly unimplemented" Thanks. I didn't take that into account (was using LDC 1.5.0 ..based on 2.075.1) Getting used to monthly compiler updates is a real challenge.. not something I'm used to ;-)
Re: betterC and noboundscheck
On Wednesday, 22 November 2017 at 15:10:40 UTC, Oleg B wrote: If I add -noboundscheck flag all works fine. dmd version is 2.076.1 Why -betterC flag not 'include' -noboundscheck flag? It's bug or in some cases it's useful? Interestingly, ldc2 will compile this ok, without the -noboundscheck flag btw. you should start using: boundscheck=off/on/safeonly flag instead i believe. https://dlang.org/dmd-windows.html#switch-boundscheck
Re: One liner alternatives for initing and pushing some values into array
On Monday, 20 November 2017 at 08:37:32 UTC, kerdemdemir wrote: bool boolList[] = { a, b, c }; D alternative(at least my D alternative) seem long. Is there any better way for initialing and pushing values at the same time. Erdem Your use of the appender method suggest to me you want to be able to append, as opposed to just initialise. module test; import std.stdio; import std.array; void main() { bool[] boolList; bool a = true; bool b = false; bool c = false; boolList ~= [ a, b, c ]; bool d = true; bool e = false; bool f = false; boolList ~= [ d, e, f ]; // ... }
Re: ESR on post-C landscape
On Thursday, 16 November 2017 at 11:52:45 UTC, Ola Fosheim Grostad wrote: Uhm, no? What do you mean by 'primary focus of program design' and in which context? I the context that, this is specifically what Stroustrup says in his book (The Design and Evolution of C++ 1994) "Simula's class concept was seen as the key difference, and ever since I have seen classes as the proper primary focus of program design." (chp1, page 20). Freud would tell us, that Stroustups obssesion with Simula, is where it all began. Stroustrup also wrote this paper in 1995 (due to all the hype of OO in the 90's), where again, he highlights how classes (and there derivatives) are his primary focus of program design: http://www.stroustrup.com/oopsla.pdf
Re: ESR on post-C landscape
On Thursday, 16 November 2017 at 06:35:30 UTC, Ola Fosheim Grostad wrote: No, classes is a powerful modelling primitive. C++ got that right. C++ is also fairly uniform because of it. Yes, I agree that classes are a powerful modelling primitive, but my point was that Stroustrup made classes the 'primary focus of program design'. Yes, that made it more uniform alright... uniformly more complicated. And why? Because he went on to throw C into the mix, because performance in Simula was so poor, and would not scale. C promised the efficiency and scalability he was after. But an efficient and scalable 'class oriented' language, means complexity was inevitable. It wasn't a bad decision on his part. It was right for the time I guess. But it set the stage for its demise I believe. People who harp about how OO is a failure don't know how to do real world modelling... I would never say OO itself is a failure. But the idea that is should be the 'primary focus of program design' .. I think that is a failure...and I think that principle is generally accepted these days. I have to wonder whether that conclusion sparked the inevitable demise of C++. There is no demise... If the next C++ doesn't get modules, that'll be the end of it...for sure. Eric should be asking a similar question about Go ..what decision has been made that sparked Go's inevitable demise - or in the case of Go, decision would be decisions. Go is growing... Yeah..but into what? It's all those furry gopher toys, t-shirts, and playful colors.. I think that's what's attracting people to Go. Google is the master of advertising afterall. Would work well in a kindergarten. But it makes me want to puke. It's so fake. a := b A practical shorthand, if you dont like it, then dont use it. Was just a senseless, unnecessary change. The immediate impression I got, was that they were trying to undo a decision, that was made when B was developed, rather doing it because it really assisted the modern programmer (what language uses that? None that I use that's for sure). And I get that feeling about other decisions they've made...as if they are just trying to correct the past. They should be focused on the future. They should have got some experienced younger programmers at google to design a language instead. I bet it wouldn't look anything like Go.
Re: ESR on post-C landscape
On Tuesday, 14 November 2017 at 11:55:17 UTC, codephantom wrote: The reason he can dismiss D, so easily, is because of his starting premise that C is flawed. As soon as you begin with that premise, you justify searching for C's replacement, which makes it difficult to envsion something like D. That's why we got C++, instead of D. Because the starting point for C++, was the idea that C was flawed. Actually, I got that wrong. Perhaps the mistake C++ made, was concluding that 'classes' were the "proper primary focus of program design" (chp1. The Design and Evolution of C++). I have to wonder whether that conclusion sparked the inevitable demise of C++. Eric should be asking a similar question about Go ..what decision has been made that sparked Go's inevitable demise - or in the case of Go, decision would be decisions. this is what did it for me: a := b
Re: ESR on post-C landscape
On Wednesday, 15 November 2017 at 09:26:49 UTC, Ola Fosheim Grøstad wrote: I don't think Go is much affected by the corporate… Umm "We made the language to help make google more productive and helpful internally" - Rob Pike https://www.youtube.com/watch?v=sln-gJaURzk 2min:55sec To be honest, it's really hard for me to be critical of something that (The) Ken Thompson was involved in ;-) ...but I've gotta speak the truth. sorry Ken. But Go sucks.
Re: ESR on post-C landscape
On Tuesday, 14 November 2017 at 16:38:58 UTC, Ola Fosheim Grostad wrote: It [C]is flawed... ESR got that right, not sure how anyone can disagree. Well I 'can' disagree ;-) Is a scalpel flawed because someone tried to use it to screw in a screw? Languages are just part of an evolutionary chain. No part of the chain should be considered flawed - unless it was actually flawed - in that it didn't meet the demands of the environment in which it was initially conceived. In that circumstance, it must be considered flawed, and evolutionary forces will quickly take care of that. But a programming language is not flawed, simply because people use it an environment where it was not designed to operate. If I take the average joe blow out of his comfy house, and put him in the middle of raging battle field, is Joe Blow flawed, because he quickly got shot down? What's flawed there, is the decision to take Joe Blow and put him in the battlefield. Corporate needs/strategy, skews ones view of the larger environment, and infects language design. I think it's infected Go, from the get Go. I am glad D is not being designed by a corporate, otherwise D would be something very different, and far less interesting. The idea that C is flawed, also skews ones view of the larger environment, and so it too infects language design. This is where Eric got it wrong, in my opinion. He's looking for the language that can best fix the flaws of C. In fact C has barely had to evolve (which is not a sign of something that is flawed), because it works just fine, in enviroments for which it was designed to work in. And those enviroments still exist today. They will still exist tomorrow..and the next day...and the next..and... So language designers..please stop the senseless bashing of C. Why does anyone need array index validation anyway? I don't get it. If you're indexing incorrectly into an array..you're a fool. btw. The conditions under which C evolved, are well documented here. It's a facinating read. https://www.bell-labs.com/usr/dmr/www/chist.pdf
Re: ESR on post-C landscape
On Tuesday, 14 November 2017 at 04:31:43 UTC, Laeeth Isharc wrote: He mentions D, a bit dismissively. http://esr.ibiblio.org/?p=7724&cpage=1#comment-1912717 The reason he can dismiss D, so easily, is because of his starting premise that C is flawed. As soon as you begin with that premise, you justify searching for C's replacement, which makes it difficult to envsion something like D. That's why we got C++, instead of D. Because the starting point for C++, was the idea that C was flawed. C is not flawed. It doesn't need a new language to replace it. If that was the starting point for Go and Rust, then it is ill conceived. One should also not make the same error, by starting with the premise that we need a simpler language to replace the complexity of the C++ language. If that was the starting point for Go and Rust, then it is ill conceived. What we need, is a language that provides you with the flexibility to model your solution to a problem, *as you see fit*. If that were my starting point, then it's unlikely I'd end up designing Go or Rust. Only something like D can result from that starting point. I'd like Eric to go write a new article, with that being the starting point. Because then, it's unlikely he would get away with being so dismissive of D.
Re: core file
On Monday, 13 November 2017 at 06:25:20 UTC, Tony wrote: I am on Ubuntu 16.04. Thanks, I didn't know that "producing a core file" was configurable, and it appears that it isn't. ok. that's because Ubuntu is not (by default) setup for developers. But you can enable core dump for your executable easily enough. e.g, if you out file is a.out, then do this: ulimit -S -c unlimited a.out (now run your program, and you'll get core file in the same dir where the program is) (this won't be remembered after a reboot, so just do it when/as required). You can view the core file using > objdump -s core Good luck understanding the contents of that ;-) Core dumps typically require some specialised expertise to analyse. Unless you're one of those specialists, then better to just run your a.out through the debugger, and forget about the core dump (until you can't) ;-)
Re: core file
On Monday, 13 November 2017 at 05:01:18 UTC, Tony wrote: I am getting the message from my program execution: "Segmentation fault (core dumped)" But I don't see a core file in the current directory or in my home directory. Is there one somewhere? Would I be able to do anything meaningful with it if it exists? More info than that is needed. What platform are you on? Do you have core dumps enabled/disabled? If you have it enabled...where does it put them? And yes, core dumps are potentially useful for debugging. However, given you're asking that question, and getting core dumps, then it might be easier for you to use the -g option when you compile, and then run your executable (or a.out) through a debugger: https://www.youtube.com/watch?v=vcVmWbYEIsk
Re: std.functional.compose compilation error
On Thursday, 9 November 2017 at 04:58:19 UTC, Chuck Allison wrote: As others have said, rename the .d file, since files are considered modules. I have since changed my notes to reflect this change. Sorry for the confusion. Chuck Allison When coming to a new language I tend to write lots of little snippets (or copy/save examples), and then I name those snippet files according to the thing being 'snipped'. But, if you do that in D (and many will do that), and you don't have some module namespace in your snippets, you'll run it the same trouble I did. I spent a day debugging because of this ;-) So, can I suggest that all code samples, by default, have: module test; (or something at the top). I'd also recommend making this issue of module namespace, one of the *first* things people learn, when coming to D, especially that fact, that the compiler will create a namespace for you (if you don't) based on the file name. So if you're writing a book, perhaps that should be in your mind too ;-) btw. As I've mentioned on other posts, the current version of GDC (as opposed to DMD and LDC) will compile such code without issue (i.e when you don't give a module name), and it will correctly work out the correct namespace to use(apparently a bug - but a nice bug ;-)
Re: How do i find a list of the methods Object implements, or maybe just locate the 'write' method?
On Wednesday, 8 November 2017 at 12:48:41 UTC, codephantom wrote: Apparently its a bug in LDC (but personally, it's a bug I like). mistyped: I meant a bug in GDC, not LDC.
Re: How do i find a list of the methods Object implements, or maybe just locate the 'write' method?
On Wednesday, 8 November 2017 at 12:17:14 UTC, bauss wrote: That's because the module name becomes `write` then. yeah I knew that. I was trying to demonstrate how (when the module name is 'write'), then the compiler is ok with: o.write; but not: write(o); even though semantically they are meant to mean the same thing. I also thought it was interesting the GDC doesn't seem to default the module namespace to the name of the file, or if it does, then it doesn't seem to have any conflict in resolving the correct namespace for the two statements(unlike DMD and LDC). Apparently its a bug in LDC (but personally, it's a bug I like). Since the original post mentioned using gdc on debian, I just wanted to point this out - because it caught be my surprise a few days ago (as I test my code across different compilers, on different platforms).
Re: How do i find a list of the methods Object implements, or maybe just locate the 'write' method?
On Wednesday, 8 November 2017 at 03:33:08 UTC, bauss wrote: -- Compiles fine with DMD: https://dpaste.dzfl.pl/95b896aa242f ahh.. that site saves it with some random temporary file name I assume. If it saved it as write.d, it likely would not compile, unless they were using gdc.
Re: How do i find a list of the methods Object implements, or maybe just locate the 'write' method?
On Wednesday, 8 November 2017 at 03:33:08 UTC, bauss wrote: -- Compiles fine with DMD: https://dpaste.dzfl.pl/95b896aa242f you saved it as?: write.d you didn't add in a module statement? and it compiled??
Re: How do i find a list of the methods Object implements, or maybe just locate the 'write' method?
On Tuesday, 7 November 2017 at 21:32:26 UTC, Adam D. Ruppe wrote: On Tuesday, 7 November 2017 at 21:25:00 UTC, dan wrote: I looked in my distribution's object.d (debian stretch, gdc, in Did you import std.stdio in the file? If so, it is calling the std.stdio.write on the object (this is called UFCS, uniform function call syntax, the language allows you to call any free function in scope with obj.foo by rewriting it to foo(obj)) it's interesting how the compiler deals with scope. --- // save this in a file named: write.d import std.stdio; void main() { auto o = new Object; // One of statements below will prevent this code from compiling. // Which one do you think it is? // btw. If I instead use gdc on debian, then it will // compile both statements just fine, and will work as expected too. o.write; write(o); } --
Re: if (int bar = .. bug or some thing
On Tuesday, 31 October 2017 at 04:27:27 UTC, Joel wrote: Ok, thanks guys. why not throw in some UFCS too...just because you can ;-) import std.stdio; void main() { int foo; if (foo.bar != 0) // would be nice if I could do: (int foo.bar != 0) { throw new Exception("foo.bar != 0"); } } auto bar(int x,) { return -10; }
std.format and floating point issue
Can anyone help me to understand why the format in the second writeln below, does not format the output with commas? void main() { import std.stdio, std.format; writeln( format("%,.1f", 84543432.951172) ); // 84,543,433.0 writeln( format("%,.0f", 84543432.951172) ); // 84543433 } --
Re: Just starting with D (linking with C++)
On Friday, 27 October 2017 at 17:14:20 UTC, sivakon wrote: I want to use C++ libraries for machine learning and deep learning. How do I add C++ libraries to my d code. on FreeBSD, I use: for C static binding: -- clang -c sample.c dmd -L-lc foo.d sample.o or ldc -L-lc foo.d sample.o for c++ static binding: --- clang++ -c sample.cpp dmd -L-lc++ foo.d sample.o or ldc -L-lc++ foo.d sample.o There is nice article here that was pretty interesting too: https://www.gamedev.net/blogs/entry/2254003-binding-d-to-c/