New to D

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 25 07:40:17 PDT 2016


On 10/22/16 1:25 AM, Mark wrote:
> Hello, Im a 3rd year Comp Sci student in Edmonton Alberta, Canada.
>
> Ive learned how to use C, and dabbled in C++ in school. Im also in a Oop
> course using Java.
>
> I picked up the book The D Programming Language by Alexrei Alexandrescu
> a few years ago.
> Lately Im really wanting to get into D, as It seems like a better
> version of C, and feels like java in a way.
>
>
>
> However;
>
> Ive run into a bit of a problem while writing some code. Im not sure if
> Im doing something wrong, or maybe the things Im using are depreciated??
>
> Code Blocks does not give any messages as to what is going wrong. I
> haven't configured anything, and am not familiar with messing around
> with IDE settings.
>
> Its directly based off of the example on page 8.
>
> here is the code that does not compile:
>
>
> import std.stdio, std.string;
>
> void main() { ... }
>
> void dict() {
>
>     uint[string] dictionary;
>
>     foreach(line; stdin.byLine()) {
>
>         //chunk = splitter(strip(line); ## errors because of splitter
>
>         foreach(word; splitter(strip(line))) { ## errors because of
> splitter ??
>
>         if(word in dictionary) continue;
>
>         //writeln(dictionary.length);  ## gives 0 ??
>
>         auto newID = dictionary.length;
>         dictionary[word] = newId;

I will note, that in addition to the other comments, this is going to 
result in corruption. Simply put, the buffer that `line` uses is reused 
for each line. So the string data used inside the associative array is 
going to change. This will result in not finding words already added 
when using the `word in dictionary` check.

You need to use dictionary[word.idup] = newId; This will duplicate the 
line into a GC string that will live as long as the AA uses it.

Alternatively, you can use byLineCopy, but this needlessly copies the 
line for each iteration, when you may find all the words in the line are 
already added.

-Steve


More information about the Digitalmars-d-learn mailing list