Concatenate 2 ranges

Vladimir Panteleev via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Nov 11 05:46:41 PST 2016


On Friday, 11 November 2016 at 13:39:32 UTC, RazvanN wrote:
> It does work, the problem is that [1, 2, 3].sort() is of type 
> SortedRange(int[], "a < b") while r is of type 
> SortedRange(Result, "a < b"). This is a problem if you want to 
> return r in a function which has return type SortedRange(int[], 
> "a < b").

If you absolutely need a `SortedRange(int[], "a < b")` without 
substitute, then there's no way except building an array that has 
the numbers sorted, which is always going to be O(n) unless you 
can place the two input arrays adjacent into memory beforehand 
somehow. However, if you just want the pre-chain ranges and 
post-chain ranges be a compatible type, you can use a class 
wrapper, such as RandomAccessFinite - thus, the assumeSorted 
result will be `SortedRange(RandomAccessFinite, "a < b")`. Note, 
though, that even though the algorithmic complexity will be O(1), 
every access to the wrapped range will go through a virtual 
method call, so it will affect performance in practice. There is 
no way around this because the type pulls in the underlying 
range's behavior, and e.g. SortedRange!(int[]) knows that the 
underlying elements are arranged linearly in memory, SortedRange 
of a chain knows that it first has to check which sub-range any 
operation will refer to, and SortedRange of a RandomAccessFinite 
knows that it just has to pass the request to a virtual class 
method which hides the underlying implementation.



More information about the Digitalmars-d-learn mailing list