> I'm trying to understand the design of ranges. Why does popFront only set > the front() property to return the next element in the range? Why not > return the element in the call to popFront right away? > > For example code like this (which doesn't work since popFront doesn't > return): void main() > { > int[] a = [1, 2]; > auto b = a.popFront; > assert(a == [2]); > assert(b == 1); > } > > Isn't it wasteful to have to call both popFront() and front() to > simultaneously remove an element from a range and return it? I mean it's > an extra function call, right?
Often, it would be wasteful to have popFront return an element, since it's perfectly legitimate to call popFront without wanting to ever see front. If the type of front is a struct, then it would have to be copied which could cost more than a function call. And both front and popFront would typically be inlined anyway (at least as long as you compile with -inline), so it's unlikely that it really costs you a function call anyway. Really, however, I believe that it's a matter of functionality. front and popFront do two very different things. One of them gives you the first element; the other removes the first element. You can call them both separately without wanting to do the other. There are plenty of cases where you want to call popFront multiple times without ever calling front, and there are plenty of cases where you want to call front without calling popFront. It _definitely_ would be a problem if front were removed in favor of having popFront return the front element, but even if you kept front and just made popFront return an element, it's conflating two separate operations into one function, which often is a bad idea. In the case of popFront, I often call popFront without wanting to look at front immediately if at all, and in most cases where you _do_ want to look at front every time, you're probably using a foreach loop and not calling popFront directly anyway. So, making popFront return an element wouldn't help you much. So, really, there's no need to make popFront return front, it's more likely to be _less_ efficient to do that, rather than more, and it's conflating two separate operations. I see little to no benefit to making popFront return anything, and it could be detrimental for it to. - Jonathan M Davis