front evaluated multiple time with joiner depending on where extra arg given

Jonathan M Davis jmdavisProg at gmx.com
Tue Oct 22 17:38:06 PDT 2013


On Wednesday, October 23, 2013 02:21:55 bearophile wrote:
> Timothee Cour:
> > auto b=[1,2,3].map!(a=>{counter++; return
> > 
> > [a];}()).joiner([0]).array;
> 
> Currently there are some problems inside some of the higher order
> functions of Phobos. So as general rule don't put impure code
> inside the functions (usually lambdas) you pass to the higher
> order functions like map, filter, etc.

Conceptually, front should be pure, but there's no reason that you can't throw 
some impure stuff in there like in this example - particularly if it's just for 
something like tracking the number of calls made. What falls apart is if front 
returns a different result without popFront being called again or front not 
being able to be called multiple times before popFront is called.

As for the multiple calls to front, there is no guarantee as to how many times 
front will be called by a particular function. A function may call front once 
and then reuse the result, or it may call front multiple times. It depends 
entirely on what it's doing. It's also quite possible that different overloads 
end up needing front a different number of times, which could result in a 
differing number of calls. But it could be argued whether it's generally more 
efficient to call front once and reuse the result or to call front multiple 
times as which is more efficient depends on stuff like how expensive it is to 
copy the element type, whether front returns by ref (possibly avoiding a 
copy), and whether front calculates anything or just returns the current 
front. Certainly, I'd argue that it's generally better practice to do the work 
in popFront, because front does frequently gets called multiple times, and you 
almost always end up calling front if you call popFront.

It's possible that map, joiner, and or array could use some efficiency 
improvements, but I wouldn't consider the difference in the number of calls to 
front to be a bug. At most, it might indicate that there are some optimization 
opportunities in one or more of those functions, and it might even be that the 
differing number of calls makes sense when you actually dig into the source 
code. I'd have to go digging to know for sure.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list