On 4/5/22 11:47 PM, Salih Dincer wrote:
On Tuesday, 5 April 2022 at 14:10:44 UTC, Steven Schveighoffer wrote:
[...]
I'd implement it probably like this (for D2):
```d
auto drop(T)(ref T[] arr, T which)
{
import std.algorithm, std.range;
auto f = arr.find(which);
debug if(f.empty) throw ...;
auto result = arr.front;
arr = arr.remove(&f[0] - &arr[0]); // god I hate this
return result;
}
```
First, you're neglecting the loop.
oops, yes, that should have been `auto result = f.front`
Second, the returned value is the
first element of the array. It should be as follows:
```d
auto drop2(T)(ref T[] arr, T which)
{
//auto f = arr.find(which);
auto f = arr.find!(a => a == which);
This is almost equivalent, but it requires a lambda and an allocation.
So I'm not sure what thing you are trying to do here.
//debug if(f.empty) throw ...;
auto result = f.front; // arr.front;
Yep, that's a bug on my part.
//arr = arr.remove(&f[0] - &arr[0]);
arr = remove!(a => a == which)(arr);
This runs through the array again, instead of just removing the one
index that you already know. And also, the original code only removed
one element, even if there were multiple matches. Yours removes them all.
return result;
}
```
We do not know the wishes of the programmer who made the development.
But it is certain that he scanned until the end of the array. So it
doesn't make sense for the resulting output to be equal to the
```which```. In summary, one line is enough:
```d
return remove!(a => a == which)(arr);
```
The return is the element that was removed, not the array after removing
the element. And even though it might feel equivalent to return the
input, we don't know how the elements compare, so the array element
might be different than the incoming parameter.
-Steve