Isn't using find with retro awkward?

spir denis.spir at gmail.com
Tue Feb 15 01:37:35 PST 2011


On 02/15/2011 05:03 AM, Jonathan M Davis wrote:
> On Monday 14 February 2011 19:35:21 Andrej Mitrovic wrote:
>> import std.stdio, std.algorithm, std.range;
>>
>> void main()
>> {
>>      writeln( find([5, 1, 2, 3, 4, 5, 1], 5) );
>>      writeln( find(retro([5, 1, 2, 3, 4, 5, 1]), 5) );
>> }
>>
>> Output:
>> [5, 1, 2, 3, 4, 5, 1]
>> [5, 4, 3, 2, 1, 5]
>>
>> The docs for find are:
>> "returns : haystack advanced such that binaryFun!pred(haystack.front,
>> needle) is true " "To find the last occurence of needle in haystack, call
>> find(retro(haystack), needle). "
>>
>> To me, if I was looking for the last element in a range I would expect to
>> get a range with the found element followed by an elements after it.
>> Obviously retro reverses the range (it just hard-wires front=back,
>> back=front for those not in the know), so this code is correct.
>>
>> Still, I would expect that finding a last element in this range:
>> [5, 1, 2, 3, 4, 5, 1]
>>
>> would return the range:
>> [5, 1]
>>
>> and not:
>> [5, 4, 3, 2, 1, 5]
>>
>> Isn't that what most people would want when they're looking for the last
>> matching element?
>
> retro revereses the whole range. What you want is something like findFromBack. Of
> course, retro isn't going to be what you want (though I guess I can understand
> why you would think that it would work if you didn't think it through).
>
> I don't think that we have any functions like findFromBack though. It's probably
> worth an enhancement request.

Indeed. The code just does what it says. I also understand Andrej's point. But 
it's a different feature; and one worth inclusion in Phobos, as Jonathan says.
Note: there is a mental trap here ;-) <iterating in reverse order !is reversing 
the array and iterating>

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list