Trouble using 'sort'

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 25 23:11:44 PDT 2016


On Tuesday, July 26, 2016 10:11:43 Bahman Movaqar via Digitalmars-d-learn 
wrote:
> On 07/26/2016 09:35 AM, Bahman Movaqar wrote:
> > I have a range which is the result of a couple of chained range
> >
> > operations, and each element is:
> >     Tuple!(string, "product", double, "price")
> >
> > Now I'd like to sort the range by "price" using:
> >     sort!((pp1, pp2) => cmp(pp1.price,  pp2.price) > 0)(theRange)
> >
> > But I get a compile time error:
> >
> > source/services.d(166,63): Error: template std.algorithm.sorting.sort
> > cannot deduce function from argument types !((pp1, pp2) =>
> > cmp(pp1.price, pp2.price) > 0)(MapResult!(__lambda5, Result)),
> > candidates are:
> >
> > 
/home/bahman/Programs/D/dmd-2.071.0/linux/bin64/../../src/phobos/std/algorithm/sorting.d(1027,1):
> >        std.algorithm.sorting.sort(alias less = "a < b", SwapStrategy ss
> >
> > = SwapStrategy.unstable, Range)(Range r) if ((ss ==
> > SwapStrategy.unstable && (hasSwappableElements!Range ||
> > hasAssignableElements!Range) || ss != SwapStrategy.unstable &&
> > hasAssignableElements!Range) && isRandomAccessRange!Range &&
> > hasSlicing!Range && hasLength!Range)
> > source/services.d(168,5): Error: var has no effect in expression
> > (theRange)
> > dmd failed with exit code 1.
>
> Alright...further experiments.  The following works:
>
>     sort!((pp1, pp2) => cmp(pp1.price,  pp2.price) > 0)(theRange)
>
> So it may be something about what kind of range I'm passing to `sort`.
> Am I right?

sort requires a random access range. Without knowing exactly which
algorithms your using, I can't say for sure that that's the problem, but
usually it is. Most of the time, you don't end up with a random access range
after chaining several range-based functions. You _can_, but it depends
entirely on which functions they are and the type of your original range.

It's frequently the case that if you want to sort a range, you have to call
array() on it to convert it to an array, and then you can sort the array.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list