www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why foreach is not nothrow even for a simple associative array?

reply Cheng Wei <rivercheng gmail.com> writes:
import std.c.stdio

int[int] g_map;

void main() {
    test();
}

nothrow void test() {
    foreach(k, v) {
       printf("%d, %d\n", k, v);
    }
}
Cannot compile with the error:

Error: _aaApply2 is not nothrow

It is not so convenient that we have to use try-catch for all
iteration even when we know that it will not throw at all.
Oct 13 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
Cheng Wei:

 nothrow void test() {
     foreach(k, v) {
        printf("%d, %d\n", k, v);
     }
 }
 Cannot compile with the error:
 
 Error: _aaApply2 is not nothrow
 
 It is not so convenient that we have to use try-catch for all
 iteration even when we know that it will not throw at all.

_aaApply2 is the function used to iterate on the associative array. It is not yet tagged with "nothrow" so you can't yet use it in an nothrow function. This is a known bug that is already in Bugzilla and will be fixed. I think it's not hard to add those tags, so if you want you will probably be able to create a little pull request that fixes this even if you don't know much about compilers. Bye, bearophile
Oct 13 2011
next sibling parent reply Cheng Wei <rivercheng gmail.com> writes:
Thanks.

The problem is that if we tag _aaApply2 as nothrow, then can we still
put throwable codes in the body of foreach?
Oct 13 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
Cheng Wei:

 The problem is that if we tag _aaApply2 as nothrow, then can we still
 put throwable codes in the body of foreach?

I see. Now in D there is purity/"throwbility" inference for templates. Is _aaApply2 allowed to become a template? Bye, bearophile
Oct 13 2011
parent Cheng Wei <rivercheng gmail.com> writes:
Yeah, the problem could be solved if _aaApply2 was a template instead of
a function.

Alternatively, maybe the compiler can skip the purity/throwbility check
for __aaApply2 and directly check the statements inside. That means to
treat the compiler generated function __aaApply2 differently than the
opApply provided by users.
Oct 13 2011
prev sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Thu, 13 Oct 2011 06:16:59 -0400, bearophile <bearophileHUGS lycos.com>  
wrote:

 Cheng Wei:

 The problem is that if we tag _aaApply2 as nothrow, then can we still
 put throwable codes in the body of foreach?

I see. Now in D there is purity/"throwbility" inference for templates. Is _aaApply2 allowed to become a template?

No, but I see no reason why _aaApply2 couldn't be overloaded with nothrow/pure versions. The underlying code would probably be a template since the actual code is no different. -Steve
Oct 13 2011