reading file byLine

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 14 11:36:52 PDT 2015


On Monday, 7 September 2015 at 10:25:09 UTC, deed wrote:
> Right, it's like
>
> int x = 3;
> // x + 5;      // Just an expression evaluated to 8,
>                // but what do you want to do with it?
>                // It won't affect your program and the
>                // compiler will give you an error.
>
> int y = x + 5; // But you can assign the expression to
>                // a new variable
> x = x + 5;     // or you can assign it back
> writeln(x);    // or you can pass it to a function.
>
>
> // For your case:
>
> int[] arr = [1, 2, 3, 2, 1, 4];
> arr.sort;          // Operating on arr in place -> arr itself 
> is mutated
> arr.writeln;       // [1, 1, 2, 2, 3, 4]
> arr.uniq;          // Not operating on arr, it's like the 
> expression
>                    // x + 5 (but no compiler error is given).
> arr.uniq.writeln;  // [1, 2, 3, 4] (Expression passed to 
> writeln)
> arr.writeln;       // [1, 1, 2, 2, 3, 4] (Not affected)
>
> int[] newArr = arr.uniq.array;
>                    // Expression put into a new array assigned 
> to newArr
> newArr.writeln;    // [1, 2, 3, 4]
> arr.writeln;       // Still the sorted array. [1, 1, 2, 2, 3, 4]
> arr = arr.uniq.array; // Now arr is assigned the uniq array
> arr.writeln;       // [1, 2, 3, 4]
>
>
> You need to know whether the function will mutate your array; 
> sort does, while uniq doesn't. If you want to do things 
> requiring mutation, but still want your original data 
> unchanged, you can duplicate the data with .dup before the 
> mutating operations, like this:
>
> int[] data = [1, 2, 2, 1];
> int[] uniqData = data.dup.sort.uniq.array;
> data.writeln;      // [1, 2, 2, 1] Unchanged, a duplicate was 
> sorted.
> uniqData.writeln;  // [1, 2]

As an aside, you should use `sort()` instead of the 
parentheses-less `sort`. The reason for this is that doing 
`arr.sort` invokes the old builtin array sorting which is 
terribly slow, whereas `import std.algorithm; arr.sort()` uses 
the much better sorting algorithm defined in Phobos.


More information about the Digitalmars-d-learn mailing list