String created from buffer has wrong length and strip() result is incorrect
When creating a string from a ubyte[], I have an invalid length and string.strip() doesn't strip off all whitespace. I'm new to the language. Is this a compiler issue? import std.string : strip; import std.stdio : writefln; int main() { const string ATA_STR = " ATA "; // this works fine { ubyte[] buffer = [' ', 'A', 'T', 'A', ' ' ]; string test = strip(cast(string)(buffer)); assert(test == strip(ATA_STR)); } // This is where things breaks { ubyte[] buff = new ubyte[16]; buff[0..ATA_STR.length] = cast(ubyte[])(ATA_STR); // read the string back from the buffer, stripping whitespace string stringFromBuffer = strip(cast(string)(buff[0..16])); // this shows strip() doesn't remove all whitespace writefln("StrFromBuff is '%s'; length %d", stringFromBuffer, stringFromBuffer.length); // !! FAILS. stringFromBuffer is length 15, not 3. assert(stringFromBuffer.length == strip(ATA_STR).length); } return 0; }
Re: Beginner ?. Why does D suggest to learn java
While d can be complex, there's nothing preventing you from starting out simple and not using all features at first. I don't understand why it's not suitable for a beginner if you use this approach... 2014-10-17 6:51 GMT+02:00 via Digitalmars-d-learn < digitalmars-d-learn@puremagic.com>: > On Friday, 17 October 2014 at 01:14:34 UTC, bearophile wrote: > >> Python is probably a better first language than Java. D is a >> little too much complex as first language. >> > > The IDE support is probably a bit better with Java/C# and using a > statically typed language as your first language has advantages, but all > are good first languages: easy to find tutorials, easy to find educational > example code, easy to find answers to typical beginner issues on > Stackoverflow… > > I personally think Logo, Processing and Scheme would be more fun as > learning tools, but they are throw-away languages. E.g. > http://turtleacademy.com/programs/en http://www.processing.org/ and many > more online programming sites. > > >
Re: Beginner ?. Why does D suggest to learn java
On Friday, 17 October 2014 at 01:14:34 UTC, bearophile wrote: Python is probably a better first language than Java. D is a little too much complex as first language. The IDE support is probably a bit better with Java/C# and using a statically typed language as your first language has advantages, but all are good first languages: easy to find tutorials, easy to find educational example code, easy to find answers to typical beginner issues on Stackoverflow… I personally think Logo, Processing and Scheme would be more fun as learning tools, but they are throw-away languages. E.g. http://turtleacademy.com/programs/en http://www.processing.org/ and many more online programming sites.
Re: extern (C) function call with const char * type will sometimes generate seg fault or core dump.
On Thursday, 16 October 2014 at 07:55:24 UTC, Mike Parker wrote: On 10/16/2014 4:54 PM, Mike Parker wrote: On 10/16/2014 12:18 PM, dysmondad wrote: Since I've added this call, my program will sometimes but not always either generate a core dump or a seg fault. It seems that the issue is with the const char * parameter. I don't have a good grasp of the difference between the way D and C work for char * types. Strings in C are arrays of chars ending with the nul terminator. Strings in D are not required to be nul terminated. String literals in D *are* nul terminated. When passing a string to a C function that takes const char*, use toStringz as Ali showed in his post. Forgot to mention -- toStringz in std.string will add the nul terminator if it is not already there. --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com Thank you very much. Because of your help, my application has far fewer seg faults and core dumps. Now, if I can just figure out why the SDL_RenderPresent call is having problems. I suspect that has more to do with the way I'm using the library than the calling convention.
Re: Beginner ?. Why does D suggest to learn java
RBfromME: I'm a newbie to programming and have been looking into the D lang as a general purposing language to learn, yet the D overview indicates that java would be a better language to learn for your first programming language. Why? Looks like D is easier than Java... Python is probably a better first language than Java. D is a little too much complex as first language. Bye, bearophile
Re: Beginner ?. Why does D suggest to learn java
On Fri, 17 Oct 2014 00:52:14 + MachineCode via Digitalmars-d-learn wrote: > I don't understand. If at least it were C but java? why not D > itself? C is *awful* as "beginner's language". never ever let people start with C if you don't hate 'em. as for D... current version of D can be used, but with some precautions. we now have excellent book by Ali. (it's great, really! i believe that it must be featured on the front dlang.org page!) but java has alot more books and tutorials. not that D is bad for beginners, it's just has a smaller userbase. and all that things with "classes are reference types and structs are not", "empty array is not empty array but is empty array" and so on D may be confusing a little. it's good to have some CS background to understood that things. just my cent and cent. signature.asc Description: PGP signature
Re: Beginner ?. Why does D suggest to learn java
On Thursday, 16 October 2014 at 22:42:21 UTC, Ali Çehreli wrote: On 10/16/2014 03:26 PM, RBfromME wrote: > I'm a newbie to programming and have been looking into the D lang as a > general purposing language to learn, yet the D overview indicates that > java would be a better language to learn for your first programming > language. Why? Looks like D is easier than Java... Here: http://dlang.org/overview.html "As a first programming language - Basic or Java is more suitable for beginners." I say, just ignore that comment. :) We should open a bug report for that page. I had great fun writing a programming book for complete beginners and found it very easy to use D for that purpose: http://ddili.org/ders/d.en/ Ali I don't understand. If at least it were C but java? why not D itself?
Re: Beginner ?. Why does D suggest to learn java
On Thu, 16 Oct 2014 22:43:11 + Brad Anderson via Digitalmars-d-learn wrote: > also shows just how old the Overview is (where do you even get a > BASIC compiler these days?). voila: http://www.freebasic.net/ ;-) signature.asc Description: PGP signature
Re: Is this a bug when creating proxies in classes?
On Monday, 25 August 2014 at 18:10:33 UTC, Gary Willoughby wrote: class Foo { private int foo; mixin Proxy!(foo); this(int x) { this.foo = x; } } Apparently Proxy doesn't work correctly inside classes. Is wrapping something inside a class particularly useful? Please comment on https://issues.dlang.org/show_bug.cgi?id=13623.
Re: Beginner ?. Why does D suggest to learn java
On Thursday, 16 October 2014 at 22:26:51 UTC, RBfromME wrote: I'm a newbie to programming and have been looking into the D lang as a general purposing language to learn, yet the D overview indicates that java would be a better language to learn for your first programming language. Why? Looks like D is easier than Java... The Overview page is ancient and needs to be rewritten. The included example sieve program reflects this. It's almost C (you'd only need to make minor changes to 4 of the lines to make it build with gcc). I'd agree that C probably isn't a good first language. The overview also suggests learning BASIC first which also shows just how old the Overview is (where do you even get a BASIC compiler these days?). There are easier languages but modern, idiomatic D is perfectly approachable for beginners in my opinion. https://issues.dlang.org/show_bug.cgi?id=13624
Re: Beginner ?. Why does D suggest to learn java
On 10/16/2014 03:26 PM, RBfromME wrote: > I'm a newbie to programming and have been looking into the D lang as a > general purposing language to learn, yet the D overview indicates that > java would be a better language to learn for your first programming > language. Why? Looks like D is easier than Java... Here: http://dlang.org/overview.html "As a first programming language - Basic or Java is more suitable for beginners." I say, just ignore that comment. :) We should open a bug report for that page. I had great fun writing a programming book for complete beginners and found it very easy to use D for that purpose: http://ddili.org/ders/d.en/ Ali
Beginner ?. Why does D suggest to learn java
I'm a newbie to programming and have been looking into the D lang as a general purposing language to learn, yet the D overview indicates that java would be a better language to learn for your first programming language. Why? Looks like D is easier than Java...
Any dub tips and tricks
Any way of using dub (on Windows or OSX). I've been trying it lately, but not much success. 1. (In the command prompt or Terminal), I create a new folder. 2. Run 'dub init' in the new folder 3. I copy the dependency from a lib/app into the dub.json file. 4. Then I just enter 'dub' In Windows I get this error (and others, but seems to go through): Failed to parse package description for dil in C:\Users\Joel\AppData\Roaming\dub\packages\dil-master\. I'm more interested in using OSX, for D.
Re: How to check i
On 10/16/2014 12:43 PM, spir via Digitalmars-d-learn wrote: denis spir is back! :) On 10/16/2014 11:46 AM, Uranuz wrote: > I have some string *str* of unicode characters. The question is how to > check if I have valid unicode code point starting at code unit *index*? It is easy if I understand the question as skipping over invalid UTF-8 sequences: import std.stdio; ubyte upperTwoBits(ubyte b) { return b & 0b1100_; } bool isUtf8ContinuationByte(char c) { enum utf8ContinuationPrefix = 0b1000_; return upperTwoBits(c) == utf8ContinuationPrefix; } void moveToValid(ref inout(char)[] s) { /* Skip over UTF-8 continuation bytes. */ while (s.length && isUtf8ContinuationByte(s[0])) { s = s[1..$]; } /* * The wchar[] overload is too complicated for Ali at this time. :) * * Please see the following function template in phobos/std/utf.d: * * private dchar decodeImpl(bool canIndex, S)(...) * if (is(S : const wchar[]) ... */ } unittest { auto s = "çde"; moveToValid(s); assert(s == "çde"); s = s[1 .. $]; moveToValid(s); assert(s == "de", s); } void moveToValid(ref const(dchar)[] s) { /* Every code unit is valid; nothing to do. */ } void main() {} Ali
Re: How to check i
On 16/10/14 20:46, Uranuz via Digitalmars-d-learn wrote: I have some string *str* of unicode characters. The question is how to check if I have valid unicode code point starting at code unit *index*? [...] You cannot do that without decoding. Cheking whether utf-x is valid and decoding are the very same process. IIRC, D has a validation func which is more or less just an alias for the decoding func ;-). Moreover, you also need to distinguish "word-character" code points from others (punctuation, spacing, etc) which requires unicode code points (Unicode the consortium provide tables for such tasks). Thus, I would recommand you to just abandon the illusion of working at the level of code units for such tasks, and simply operate on strings of code points. (Why do you think D has them builtin?) denis
Re: how to get the \uxxxx unicode code from a char
On Tuesday, 14 October 2014 at 20:08:03 UTC, Brad Anderson wrote: On Tuesday, 14 October 2014 at 20:05:07 UTC, Brad Anderson wrote: https://github.com/D-Programming-Language/phobos/blob/master/std/json.d#L579 Oops. Linked the the parser section. I actually don't see any unicode escape encoder in here. Perhaps he meant the upcoming JSON module. Wow... the current std.json doesn't do string encoding? I knew it was bad, but... In any case, yes, I mentioned JSON because strings are supposed to be encoded exactly the way you're asking. It was easier to point at that than try to outline the process explicitly.
Re: Using __traits to find functions in sub-modules
On Thursday, 16 October 2014 at 18:39:50 UTC, nrgyzer wrote: Hi, I'm using structs to describe my functions: struct example { string name; uint someValue; } module mod.example1; @example("example1", 1) void myFunction() { // do something } module mod.example2; @example("example2", 2) void myFunction() { // do something } I'm using the struct to describe functions in different modules. Now, I want add all functions which are described using the example-struct to an array during compile time. But how can I do this? I know, I can use __trait(allMembers, mod.example1) and __trait(allMembers, mod.example2), but I only want specify the parent module (mod), for instance: void main() { foreach (member, __traits(allMembers, mod)) { writeln(member); } } But this only shows "object" - nothing else. No sub-modules like mod.example1 or mod.example2. So, how can I find all functions that are described using my structure during compile time and add them to an array? I already tried this: void main() { foreach (cmodule; ModuleInfo) { foreach (submodule; __traits(allMembers, cmodule)) { // ... also tried: foreach (submodule; __traits(allMembers, mixin(cmodule.name))), cmodule.name is not available during compile time... } } } But it always stats that 'cmodule' has no members. Does anyone know how to solve the problem? perhaps you could get somewhere by using a package.d in every package? If it needs to work on packages you don't control then I don't really know :/
Re: Using __traits to find functions in sub-modules
On Thu, 16 Oct 2014 18:39:48 + nrgyzer via Digitalmars-d-learn wrote: > But it always stats that 'cmodule' has no members. Does anyone > know how to solve the problem? there is no non-hackish solution, afaik. there is no even hackish, but reliable one. signature.asc Description: PGP signature
How to check i
I have some string *str* of unicode characters. The question is how to check if I have valid unicode code point starting at code unit *index*? I need it because I try to write parser that operates on string by *code unit*. If more precisely I trying to write function *matchWord* that should exctract whole words (that could consist not only English letters) from text. This word then compared with word from parameter. I want to not decode if it is not necessary. But looks like I can't do it without decoding, because I need to know if current character is letter of alphabet and not punctuation or whitespace for example. There is how I think this look like. In real code I have template algorithm that operates on differrent types of strings: string, wstring, dstring. struct Lexer { string str; size_t index; bool matchWord(string word) { size_t i = index; while( !str[i..$].empty ) { if( !str.isValidChar(i) ) { i++; continue; } uint len = str.graphemeStride(i); if( !isAlpha(str[i..i+len]) ) { break; } i++; } return word == str[index..i]; } } It is just a draft of idea. Maybe it is complicated. What I want to get as a result is logical flag (matched or not) and position should be set after word if it is matched. And it should match whole words of course. How do I implement it correctly without overhead and additional UTF decodings if possible? And also how could I validate single char of string starting at code unit index? Also I don't like that graphemeStride can throw Exception if I point to wrong possition. Is there some nothrow version? I don't want to have extra allocations for exceptions.
Using __traits to find functions in sub-modules
Hi, I'm using structs to describe my functions: struct example { string name; uint someValue; } module mod.example1; @example("example1", 1) void myFunction() { // do something } module mod.example2; @example("example2", 2) void myFunction() { // do something } I'm using the struct to describe functions in different modules. Now, I want add all functions which are described using the example-struct to an array during compile time. But how can I do this? I know, I can use __trait(allMembers, mod.example1) and __trait(allMembers, mod.example2), but I only want specify the parent module (mod), for instance: void main() { foreach (member, __traits(allMembers, mod)) { writeln(member); } } But this only shows "object" - nothing else. No sub-modules like mod.example1 or mod.example2. So, how can I find all functions that are described using my structure during compile time and add them to an array? I already tried this: void main() { foreach (cmodule; ModuleInfo) { foreach (submodule; __traits(allMembers, cmodule)) { // ... also tried: foreach (submodule; __traits(allMembers, mixin(cmodule.name))), cmodule.name is not available during compile time... } } } But it always stats that 'cmodule' has no members. Does anyone know how to solve the problem?
Re: Really in need of help with std.container.array.d
On Thursday, 16 October 2014 at 13:56:18 UTC, Robert burner Schadek wrote: I'm stuck. Need help. I will give it a try Thank you.
Re: Really in need of help with std.container.array.d
On Wednesday, 15 October 2014 at 21:15:14 UTC, Nordlöw wrote: Comint exited abnormally with code 1 at Wed Oct 15 23:14:37 I'm stuck. Need help. I will give it a try
Re: Simple import question
On 10/16/14 6:59 AM, Rei Roldan wrote: On Wednesday, 15 October 2014 at 16:11:22 UTC, Steven Schveighoffer wrote: *snip* You might of missed Adam's response up there: " But the best way is to explicitly pass all the file names to the compiler: dmd yourfile.d file2.d folder/file3.d and so on... Doing that will serve you best in the long run, it will work with any module name and will link better too. " No, I didn't miss it. As I said, you can do this with mismatched module and file names, but you will encounter issues if your files need to be imported elsewhere. Note, you can send all the files to the compiler, AND name your files/directories after your modules/packages. Matching the names actually gives you the most options. I also prefer explicitly telling the compiler what I want to be compiled instead of the "start here and pull everything you can find" approach. What I am specifically identifying as a problem is if you purposely do not name your files and directories after your module structure. Then you are REQUIRED to pass all the files to the compiler, and this doesn't work out well if you just want to import them (and not compile them), e.g. for a pre-compiled library. -Steve
Re: Simple import question
On Thursday, 16 October 2014 at 10:59:29 UTC, Rei Roldan wrote: On Wednesday, 15 October 2014 at 16:11:22 UTC, Steven Schveighoffer wrote: *snip* You might of missed Adam's response up there: " But the best way is to explicitly pass all the file names to the compiler: dmd yourfile.d file2.d folder/file3.d and so on... Doing that will serve you best in the long run, it will work with any module name and will link better too. " I also prefer explicitly telling the compiler what I want to be compiled instead of the "start here and pull everything you can find" approach. i think you are going in right way
Re: Simple import question
On Wednesday, 15 October 2014 at 16:11:22 UTC, Steven Schveighoffer wrote: *snip* You might of missed Adam's response up there: " But the best way is to explicitly pass all the file names to the compiler: dmd yourfile.d file2.d folder/file3.d and so on... Doing that will serve you best in the long run, it will work with any module name and will link better too. " I also prefer explicitly telling the compiler what I want to be compiled instead of the "start here and pull everything you can find" approach.
Re: Using return type of a predicate function as a template
On Thursday, 16 October 2014 at 08:18:02 UTC, Atila Neves wrote: This works: import std.range; auto groupBy(alias func, R)(R values) if (isInputRange!R) { alias K = typeof(func(values.front)); alias V = ElementType!R[]; V[K] grouped; foreach(value; values) grouped[func(value)] ~= value; return grouped; } Thank you, that is surprisingly straightforward :) Edwin
Re: Using return type of a predicate function as a template
This works: import std.range; auto groupBy(alias func, R)(R values) if (isInputRange!R) { alias K = typeof(func(values.front)); alias V = ElementType!R[]; V[K] grouped; foreach(value; values) grouped[func(value)] ~= value; return grouped; } unittest { struct Test { string a; double b; } auto values = [Test( "a", 1 ), Test( "a", 2 ), Test( "b", 3 )]; auto grouped = values.groupBy!(a => a.a); assert( grouped["a"].length == 2 ); assert( grouped["a"][1].b == 2 ); assert( grouped["b"].length == 1 ); assert( grouped["b"][0].b == 3 ); } Atila On Thursday, 16 October 2014 at 08:04:08 UTC, Edwin van Leeuwen wrote: I am trying to implement a groupBy function that groups by the return type of a predicate. Currently I have to define the returntype of the predicate for it to compile. Is there a way to get the return type at compile time and use it. The code: V[K] groupBy( alias func, K, V )( V values ) { V[K] grouped; foreach ( value ; values ) { grouped[func( value )] ~= value; } return grouped; } unittest { struct Test { string a; double b; } auto values = [Test( "a", 1 ), Test( "a", 2 ), Test( "b", 3 )]; auto grouped = values.groupBy!( (a) => a.a, string ); assert( grouped["a"].length == 2 ); assert( grouped["a"][1].b == 2 ); assert( grouped["b"].length == 1 ); assert( grouped["b"][0].b == 3 ); } So the above works, but I need to call it with: values.groupBy!( (a) => a.a, string ); Ideally I would call it instead with: values.groupBy!( (a) => a.a ) and it would infer that the template K needs to be a string, since that is the return type of (a) => a.a. Cheers, Edwin
Re: Very strange compilation error
On Wednesday, 15 October 2014 at 21:28:05 UTC, Nils Boßung wrote: On Wednesday 15 October 2014 22:13, John Colvin wrote: On Wednesday, 15 October 2014 at 19:29:27 UTC, Jack Applegame wrote: I don't understand why this code doesn't compile: http://dpaste.dzfl.pl/dfd8df7f80ad that should be immutable(ubyte)[] not immutable ubyte[] which is equivalent to immutable(ubyte[]). You can't overwrite immutable data, hence the error. Then Foo1 foo1; foo1 = Foo1(); // compiles shouldn't compile either. Good point. That's an accepts-invalid IMO. Nonetheless: union { string a; immutable ubyte[] b; } is broken, it is effectively casting away immutability. union { string a; immutable(ubyte)[] b; } is the correct approach.
Using return type of a predicate function as a template
I am trying to implement a groupBy function that groups by the return type of a predicate. Currently I have to define the returntype of the predicate for it to compile. Is there a way to get the return type at compile time and use it. The code: V[K] groupBy( alias func, K, V )( V values ) { V[K] grouped; foreach ( value ; values ) { grouped[func( value )] ~= value; } return grouped; } unittest { struct Test { string a; double b; } auto values = [Test( "a", 1 ), Test( "a", 2 ), Test( "b", 3 )]; auto grouped = values.groupBy!( (a) => a.a, string ); assert( grouped["a"].length == 2 ); assert( grouped["a"][1].b == 2 ); assert( grouped["b"].length == 1 ); assert( grouped["b"][0].b == 3 ); } So the above works, but I need to call it with: values.groupBy!( (a) => a.a, string ); Ideally I would call it instead with: values.groupBy!( (a) => a.a ) and it would infer that the template K needs to be a string, since that is the return type of (a) => a.a. Cheers, Edwin
Re: extern (C) function call with const char * type will sometimes generate seg fault or core dump.
On 10/16/2014 4:54 PM, Mike Parker wrote: On 10/16/2014 12:18 PM, dysmondad wrote: Since I've added this call, my program will sometimes but not always either generate a core dump or a seg fault. It seems that the issue is with the const char * parameter. I don't have a good grasp of the difference between the way D and C work for char * types. Strings in C are arrays of chars ending with the nul terminator. Strings in D are not required to be nul terminated. String literals in D *are* nul terminated. When passing a string to a C function that takes const char*, use toStringz as Ali showed in his post. Forgot to mention -- toStringz in std.string will add the nul terminator if it is not already there. --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com
Re: extern (C) function call with const char * type will sometimes generate seg fault or core dump.
On 10/16/2014 12:18 PM, dysmondad wrote: Since I've added this call, my program will sometimes but not always either generate a core dump or a seg fault. It seems that the issue is with the const char * parameter. I don't have a good grasp of the difference between the way D and C work for char * types. Strings in C are arrays of chars ending with the nul terminator. Strings in D are not required to be nul terminated. String literals in D *are* nul terminated. When passing a string to a C function that takes const char*, use toStringz as Ali showed in his post. --- This email is free from viruses and malware because avast! Antivirus protection is active. http://www.avast.com
Re: extern (C) function call with const char * type will sometimes generate seg fault or core dump.
On 10/15/2014 08:18 PM, dysmondad wrote: > Since I've added this call, my program will sometimes but not always > either generate a core dump or a seg fault. It seems that the issue is > with the const char * parameter. > > I don't have a good grasp of the difference between the way D and C work > for char * types. The call to loadTexture uses a literal for the file > name, i.e. "resources/ball.png". > > // d lang bindings for C function > alias void SDL_Renderer; > alias void SDL_Texture; > extern (C) SDL_Texture * IMG_LoadTexture(SDL_Renderer * renderer, const > char * file); > > // d lang call to extern (C) function > SDL_Texture* loadTexture( SDL_Renderer * ren, const char * file ) > { > SDL_Texture * loadedImage = IMG_LoadTexture( ren, file ); > return loadedImage; > } I wouldn't expect to see strings represented as 'const char *' on D side. The more convenient and safer option is to use 'string' on the D side and pass it through toStringz() before calling C. The D function now takes 'string' and calls toStringz() on it: SDL_Texture* loadTexture( SDL_Renderer * ren, string file ) { SDL_Texture * loadedImage = IMG_LoadTexture( ren, file.toStringz); return loadedImage; } However, note the lifetime issue: http://dlang.org/phobos/std_string.html#.toStringz Ali