reading file byLine

deed via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 7 03:25:07 PDT 2015


On Sunday, 6 September 2015 at 22:04:55 UTC, Namal wrote:
> oh, sorry. But I found out what I have been doing wrong besides 
> that.
>
> arr.sort.uniq;
>
> uniq(arr) or arr.sort.uniq; compiles but doesn't store it in 
> the arr array, I need to store it in a new one.

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]



More information about the Digitalmars-d-learn mailing list