std.container & ranges

Max Wolter awishformore at gmail.com
Sun Oct 30 12:53:02 PDT 2011


On 10/30/2011 6:45 PM, Jonathan M Davis wrote:
> On Sunday, October 30, 2011 11:38:30 Max Wolter wrote:
>> Hello there.
>>
>> I seem to be having problems wrapping my head around how to use the
>> ranges in the context of containers in phobos. Specifically, I can't
>> seem to figure out how to remove an element from a linked list.
>>
>>            foreach(cell; organism)
>>            {
>>               if(cell.x == x&&  cell.y == y)
>>               {
>>                  organism.stableLinearRemove(cell);
>>                  break;
>>               }
>>            }
>>
>> mind.d(123): Error: function
>> std.container.SList!(Cell).SList.linearRemove (Range r) is not callable
>> using argument types (Cell)
>> mind.d(123): Error: cannot implicitly convert expression (cell) of type
>> cell.Cell to Take!(Range)
>>
>> I somehow get the feeling such a basic operation should just...work?
>
> linearRemove (and stableLinearRemove) takes a _range_ not a value. cell is an
> element in the list, not a range over the list. The range that it takes must
> be either of type SList.Range or Take!(SList.Range). You get that range by
> slicing an SList. Take!(SList.Range) is for the case where you want only a
> portion of the beginning of a range rather than the whole range. Your example
> actually has a really simple solution:
>
> auto found = find!((a){return a.x == x&&  a.y == y;})(organism[]);
> organism.stableLinearRemove(take(found, 1));
>
> It finds the element in the list that you're looking for, and then it passes a
> range with that one element to stableLinearRemove so that it'll remove it.
>
> - Jonathan M Davis

Hello there.

Thank you very much for the explanation.

However, while I really liked the concept of ranges in Andrei's book and 
a lot of it seems intuitive and faster than using iterators, I can't 
shake the feeling that in this case, it's just unnecessarily convoluted.

Maybe it's just the fact that the container library is still very basic, 
but I don't think I should go through such a complicated procedure to 
remove an known element from a list. It's just not a "very simple" or 
intuitive solution, which is something I came to love D for thus far.

/Max


More information about the Digitalmars-d-learn mailing list