Can I count on the order in which the sections are saved?
Let's say I have a sorted array like:
myArray = [1, 2, 3, 4, 5, 6]
Let's assume that on it Enumerable#partition
:
p myArray.partition(&:odd?)
Should the output always be as follows?
[[1, 3, 5], [2, 4, 6]]
This is not stated in the documentation; here's what he says:
partition {| obj | block} → [true_array, false_array]
section → an_enumeratorReturns two arrays, the first of which contains the enumeration elements for which the block evaluates to true, the second contains the rest.
If no block is specified, a counter is returned instead.
But it is logical to assume that it partition
works this way.
Through testing the Matz interpreter, it looks like the output works like this and it makes sense for it. However, can I expect to partition
work this way regardless of Ruby version or interpreter?
Note: I did implementation-agnostic because I couldn't find any other tag that describes my concern. Feel free to change the tag to something better if you know about it.
source to share
No, you cannot rely on an order. The reason is parallelism.
A traditional sequential implementation partition
would loop through each element of the array, evaluating the block in order. As each call odd
returns, it is immediately put into the corresponding true or false array.
Now imagine an implementation that takes advantage of multiple processor cores. It still iterates through the array in order, but each call odd
might fail. odd(myArray[2])
can go back to odd(myArray[0])
, leading to [[3, 1, 5], [2, 4, 6]]
.
List processing idioms such as partition
that run a list through a function (most of Enumerable ) benefit greatly from parallel processing, and most computers these days have multiple cores. I wouldn't be surprised if Ruby's implementation takes advantage of this in the future. The authors of the API documentation for Enumerable have probably carefully left out any mention of ordering a process to keep this optimization opportunity open.
source to share