In expression for array

Christopher Wright dhasenan at gmail.com
Fri Jan 25 05:39:27 PST 2008


bearophile wrote:
> kede wrote:
>>  if ('i' in eyes)
>>  ...
>>
>> as a simple replacement for the more verbose
>>  foreach(c; eyes)
>>    if (c == 'i')
>>      ...
> 
> I want to add few things to this discussion:
> - D already has opIn and opIn_r, so it's just a matter of using it.
> - If you use a language with the in built in (D has it already, but I meant for arrays), like Python, you can quickly understand why it's very good to have it built-in. (Generally if you come from a language that lacks something, then it becomes less easy to see why/where it's useful. I know some things aren't good if you put them in another language, but it's not this situation, I think).
> - Using the foreach(c; eyes) if (c == 'i'){} pattern is bad because you always use a O(n) scan regardless what that "eyes" is. But maybe "eyes" is an object with a opIn_r method that is O(ln n) or O(1), and you miss it. Instead if you use "in" (that is you use opIn_r) you always use the faster way of finding the presence of an item the object allows you to (if no opIn_r is defined, but opApply is defined, then the "in" operator must automatically call opApply to perform a scan).
> - So using "in" makes code shorter, more flexible, more type-agnostic (generic), simpler to read, potentially faster and more standard :-)
> 
> Bye,
> bearophile

bool has(T)(T[] arr, T elem) {
    foreach (a; arr) if (a == elem) return true;
    return false;
}

if (myarray.has(3)) {
    // ...
}

Just as good, imhoe. You can't avoid a linear scan unless you know 
whether the array is sorted.



More information about the Digitalmars-d mailing list