Question about order

Why is there a different outcome .
The first example is creating an array with numbers filled with 1…100
On the second line I randomize those numbers , notice that there are doubles
The third line sorts the array ( the doubles are gone )
The fourth line plots it , result a linear line going from 1 to 100

In the second example all is done in one line of code(except the plotting, )
So when random and sort are executed on the same line , it keeps the doubles which results in a different curve .

/////example 1 
c=(1..100);
c.rand;
c.sort;
c.plot;
/////example 2
c=(1..100).rand.sort;
c.plot;
/////////

And yep beginners mistake :slight_smile:
In the first example , the plotting is done on variable a which hasn’t been reassigned , iow it’s still an array (1…100)
Correct outcome

/////example 1 
c=(1..100);
c=c.rand;
c.sort;
c.plot;

Still have a question
In my initial post it was obvious that variable a has not been assigned a new value , thus the plotting happened on the array (1…100)
But here in this code again when executing each line separately .
Example 1
line 1 a is an array from 1…100
line 2 a is assigned a new randomized version of the array
Then a is sorted ( no new assignment , and there are doubles in the rndm array)
Then when plotted , it gives a graph of the randomized sorted version
I marked the duplicates-doubles on the graph with red rectangles .
How is possible , because the sorted version is not assigned , yet it is shown on the graph?

Example 2 ,
c = is array filled with 1…100
then this array is randomized , c is NOT given a new value
When plotted , it shows a straight linear curve going from 1 to 100 , which is normal because c is still the inital array and the randomizaton has not been plotted.
My question is how is it possible , in example 1 the sorting has been plotted while it was NOT reassinged to a , seems like it was held in temp. memory ?’
In example 2 , the randomization is totally disregarded when plotting because it was NOT assigned .to c
So why are these two unassigned lines ( sort in example 1 , and rand in examp 2 ) treated differently ?

/////// example 1 
a=(1..100);
a=a.rand;
a.sort;
a.plot;
 
/////example 2 
c=(1..100);
c.rand;
c.plot;
/////example 2


1 Like

yep - apparently some methods do work in place - most(all?) of the methods in Array return a new array, so you have to reassign. But some methods ( .sort is a method of SequenceableCollection ) will change the receiver. Unfortunately you just have to learn these. Or to be safe you can always reassign the variable.

I wonder if there is some shorthand that could make clear which methods on Collections act in place? .sortInPlace perhaps? or .sortP? Or, like in Haskell and such forbid these!