Removing from SList (std.container)...
Tobias Pankrath
tobias at pankrath.net
Wed Jun 27 03:43:46 PDT 2012
> Can you show me an example or removing a number?
I think that is a prime example of why std.container sucks both
in documentation and implemantation.
We really need to improve here, sadly development seems to be
bottlenecked by Andrei working on on allocator proposal. And
Andrei is busy at the moment.
Here is the solution. You actually need 4 different modules from
phobos to do this and it is absolutely not obvious how to do it.
import std.algorithm;
import std.range;
import std.container;
import std.array;
void main(string[] args)
{
SList!int list = [1,2,3,4,5]; // our list
writeln(list.array()); // need to create an array to print
nicely
auto pos = find(list[], 4); // we need a range, so we search
for the number
auto pos2 = take(pos, 1); // but find returns a range over
the rest, so take one
list.linearRemove(pos2); // remove it
writeln(list.array()); // print it
}
I needed to look it up myself and didn't find a solution on first
try.
My first error: You can't just do find(list, 4), because an SList
is not a range by itself. So you need opSlice (list[]) to get a
range over list.
Then I knew already that find gives me not what I want. I somehow
need to restrict the range pos to the first element. But how to
do it? I wouldn't expect a newcomer to come up with a solution
on its own, because pos[0..1] will not work on a forward range.
Luckily I knew std.range.takeOne.
But hold! takeOne(pos) does not work, you need take(pos, 1).
That sucks.
None of the above is stated explicitly in the documentation. I
knew that the container generally need a range that was extracted
from them. How should I know that in this special case a range
from std.range will work, too? And not all ranges work, only the
one from take.
More information about the Digitalmars-d-learn
mailing list