I am currently learning D and are taking the baby steps, so please bear with me.
I am reading the book simply titled "The D Programming Language". I am using the D-IDE for my code. I am currently writing a program, which is supposed to add words to it's vocabulary (dictionary) if the book doesn't already have the word.
The problem is though, that the code the book provides 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 a problem that I am so new to D.
The code looks as such:
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 experienced with Java, I guess the error means that the method doesn't exist and that it therefor tried to handle it as a variable, but that doesn't exist either. So I tried to change it to "split" instead. This produce another error at dictionary saying: Error: associative arrays can only be assigned values with immutable keys, not char[]
So I don't really know what to do to solve this and make it work. So frustrating when code from books that are supposed to teach you, don't work. I am using dmd2.
The splitter you want is located in the std.algorithm.iteration
module (previously std.array
, but it moved in 2016). Add it to your import and that should go away.
The other thing is dictionary[word]. That will have to be dictionary[word.idup] instead.
The reason for that is the line brought in by stdin.byLine is in a temporary buffer (for maximum performance by avoiding memory allocations). When you get the next line, it will overwrite the previous one.
You don't want that in an AA: the keys will get all confused. The .idup makes a copy that never changes.
(The reason the book doesn't have the idup is probably because that the code there used to compile, but it didn't really work right so that was considered a bug.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With