!in

daoryn asdf at sfa.we
Wed Feb 17 08:45:00 PST 2010


bearophile Wrote:

> I've seen this change:
> http://dsource.org/projects/dmd/changeset/388
> 
> !in is one of the things I have asked in the first list of requests I have posted in this newsgroup a lot of time ago :-) Glad to see few of those things get implemented. Thank you.
> 
> The related thing I was asking for, is to use "in" for a linear search of single items inside an array, as in Python, a very handy thing that's used frequently (CPython it also implements an efficient algorithm to search for a substring: http://effbot.org/zone/stringlib.htm  But probably Andrei wants such substring search to be a separated algorithm, even if it's very specifically tuned for strings only and not for arrays in general. I can understand this).
> 
> Bye,
> bearophile

I tried to rename the function opIn hoping it would get automatically assumed to be synonim to the "in" operator, but ended up having to put it on my "common.d" file and explicitly use it.

public bool inArray(T)(in const(T)[] array, in T elem) pure
{
	foreach(size_t i, T e; array) if (e==elem) return true;
	return false;
}

Would be nice also to have a general search function such as

public int findFirst(T)(in const(T)[] haystack, in const(T)[] needle) pure
in
{
	assert(haystack.length!=0, "haystack.length on slices!() == 0");
	assert(needle.length!=0, "haystack.length on slices!() == 0");
	assert(haystack.length>=needle.length, "Needle is bigger than haystack.");
}
out (result)
{
	assert(result>=-1);
	assert(result<=(haystack.length-needle.length));
}
body
{
	const int end=(haystack.length-needle.length)+1;
	for (int i=0; i<end; i++) if (haystack[i..i+needle.length]==needle) return i;
	return -1;
}

I found something similar on std.array but discovered that syntax was very obscure and ended up making my own functions.



More information about the Digitalmars-d mailing list