Improving std.algorithm.find

Philippe Sigaud philippe.sigaud at gmail.com
Mon Jul 19 23:42:06 PDT 2010


On Tue, Jul 20, 2010 at 00:36, Dmitry Olshansky <dmitry.olsh at gmail.com>wrote:


> Ah yes, but I regularly use algorithms structs as return values, like this:
>>
>> auto nTimes(E, R)(E multiplier, R range)
>> {
>>    return map!((ElementType!R e) { return e*multiplier;})(range);
>> }
>>
>

> Try this workaround, replacing delegate with nested function, works for me:
>
> auto nTimes(E, R)(E multiplier, R range){
>    ElementType!R fun(ElementType!R e) { return e*multiplier; }
>    return map!(fun)(range);
> }
> For some reason, compiler never plays nice with map, and I believe there
> are some issues with current implementation (2.047 release ) that Andrei
> (hopefully) fixed in recent commit.
>
>
Hmm, using a nested function was the first thing I tried, and it didn't work
at the time. Good to know it's a bug. right now, it does not work, though:


void main()
{
    auto arr = [0,1,2,3,4];
    writeln(array(nTimes(3, arr))); // prints 0, then four big numbers: it's
stomping on another part of memory?
}

Strangely, even using 0 as a multiplier does not work. Using .save() in
nTimes neither.

You see, these kinds of issues all have solutions (in that particular case,
the workaround is a bit complicated but works in practice), but they are
cumbersome and limit my usage of std.algorithms.

FWIW, the workaround I used there is to take the multiplier, call repeat on
it to make it a range (3,3,3,3 ...), zip the two ranges together and call
map with a function like this:  times(A,B)(Tuple!(A,B) t) { return
t._0*t._1;}
so, you get:  (0,3), (1,3), (2,3), ... and then 0,3,6, etc.
Extension of this idea saved me many times.


Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20100720/830958ef/attachment.html>


More information about the Digitalmars-d mailing list