www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Strange behavior of the function find() and remove()

reply "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
This is normal behavior?

import std.stdio;
import std.algorithm;

void main() {

	auto a = [3, 5, 8];

	writeln(find(remove(a, 1), 5).length != 0);     // prints false
	writeln(a);		// prints [3, 8, 8] ???
}
Mar 08 2015
next sibling parent reply "safety0ff" <safety0ff.dev gmail.com> writes:
On Sunday, 8 March 2015 at 21:34:25 UTC, Dennis Ritchie wrote:
 This is normal behavior?
Yes it is normal, there are two potential points of confusion: - remove mutates the input range and returns a shortened slice to the range which excludes the removed element. - remove takes an index as its second argument, not an element. For more information see: https://issues.dlang.org/show_bug.cgi?id=10959
Mar 08 2015
parent "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
On Sunday, 8 March 2015 at 21:58:20 UTC, safety0ff wrote:
 On Sunday, 8 March 2015 at 21:34:25 UTC, Dennis Ritchie wrote:
 This is normal behavior?
Yes it is normal, there are two potential points of confusion: - remove mutates the input range and returns a shortened slice to the range which excludes the removed element. - remove takes an index as its second argument, not an element. For more information see: https://issues.dlang.org/show_bug.cgi?id=10959
Thanks.
Mar 08 2015
prev sibling parent "anonymous example.com" <anonymous example.com> writes:
On Sunday, 8 March 2015 at 21:34:25 UTC, Dennis Ritchie wrote:
 This is normal behavior?

 import std.stdio;
 import std.algorithm;

 void main() {

 	auto a = [3, 5, 8];

 	writeln(find(remove(a, 1), 5).length != 0);     // prints false
 	writeln(a);		// prints [3, 8, 8] ???
 }
Yes, works as designed. `remove` writes over removed slots and returns shrunk (shrinked?) slice. It does not shrink the range at the call site. To update `a`, write the result of `remove` to it: writeln(find(a = remove(a, 1), 5).length != 0); // still false writeln(a); // prints [3, 8]
Mar 08 2015