In expression for array
bearophile
bearophileHUGS at lycos.com
Thu Jan 24 23:25:56 PST 2008
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
More information about the Digitalmars-d
mailing list