Code from the book does not work

I am currently studying D and taking baby steps, so please bear with me.

I am reading a book simply called "Programming Language D". I am using D-IDE for my code. I am currently writing a program that should add words to a dictionary (dictionary) if the book does not already have a word.

The problem is that the code provided by the book is invalid, and instead of just moving on and reading what the results should be, etc., I wanted to try and solve it. Of course, the problem is that I'm so new to D.

The code is as follows:

import std.stdio, std.string; void main() { uint[string] dictionary; foreach(line; stdin.byLine()) { // Break sentence into words // Add each word in the sentence to the vocabulary foreach(word; splitter(strip(line))) { if(word in dictionary) continue; // Nothing to do auto newID = dictionary.length; dictionary[word] = newID; writeln(newID, '\t', word); } } } 

The IDE says Error: undefined identifier splitter , and since I am pretty good at Java, I think the error means that the method does not exist and that it tried to treat it as a variable, but that also does not exist. So I tried changing it to "split". This leads to another error in the dictionary phrase: Error: associative arrays can only be assigned values with immutable keys, not char[]

Therefore, I do not know what to do to solve this problem and make it work. So it’s frustrating when the code from the books that should teach you does not work. I am using dmd2.

+6
source share
1 answer

The splitter you want is in the std.algorithm.iteration module (formerly std.array , but it moved in 2016). Add it to your import and this should disappear.

Another thing is the dictionary [word]. Instead, it will be a dictionary [word.idup].

The reason for this is the line given by stdin.byLine in a temporary buffer (for maximum performance, avoiding memory allocation). When you get the next line, it will overwrite the previous one.

You do not want this to be in AA: the keys are all confused .. idup makes a copy that never changes.

(The reason the book does not have idup is probably because the code used there to compile, but actually does not work correctly, is therefore considered an error.)

+10
source

All Articles