Dynamic / resizable array type, and a crash problem
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 15 12:23:49 PDT 2015
On Thursday, 14 May 2015 at 20:50:05 UTC, ivoras wrote:
> I'm experimenting to get a feel for the language. Do you have a
> suggestion about this example code: https://goo.gl/F7LCAg to
> make it more "D-like", idiomatic?
Quoting from the code:
> for (int i = 0; i < count; i++) {
foreach(i; 0 .. count)
> try {
> auto choices = markov[current];
[...]
> } catch (RangeError e) {
> break;
> }
Don't catch Errors. Use the `in` operator to check if `current`
is in `markov`:
if(current !in markov) break;
Or avoiding double lookup:
string[]* choicesp = current in markov;
if(choicesp is null) break;
auto choices = *choicesp;
> int main(string[] args)
You cam omit the return type and `args` if you're not going to
use them:
void main()
> foreach (c_line; stdin.byLine()) {
> auto line = to!string(c_line);
Could use byLineCopy:
foreach(line; stdin.byLineCopy)
> if (prev_token in markov) {
> markov[prev_token] ~= token;
> } else {
> markov[prev_token] = [token];
> }
I think you can just go with appending here:
markov[prev_token] ~= token;
But I'm not 100% sure about the implications.
More information about the Digitalmars-d-learn
mailing list