www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why is std.algorithm.reduce impure?

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
Why is std.algorithm.reduce not marked pure? It makes it impossible to
do things like this:

	pure const int product(int[] args) {
		return reduce!"a * b"(args);
	}


T

-- 
Life is unfair. Ask too much from it, and it may decide you don't deserve what
you have now either.
Mar 06 2012
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Tuesday, 6 March 2012 at 22:39:20 UTC, H. S. Teoh wrote:
 Why is std.algorithm.reduce not marked pure?

It doesn't have to be - templates are inferred to be pure or not. If you take the const off that signature, your example works in today's dmd.
Mar 06 2012
parent bearophile <bearophileHUGS lycos.com> writes:
H. S. Teoh:

 But why can't 'this' be const? For example, why does the compiler reject
 this:
 
 	class A {
 		int[] data;
 		pure const int sum() {
 			return reduce!"a*b"(data);
 		}
 	}
 
 I'm not modifying data at at all, so why should it be an error?

I think it's a small bug in std.algorithm.reduce, is this in Bugzilla already? import std.algorithm: reduce; void main() { const data = [2, 3, 4]; int r1 = reduce!q{a * b}(0, data); // OK int r2 = reduce!q{a * b}(data); } In std.algorithm.reduce there is also this (now bug 2443 is fixed) at about line 723: // For now, just iterate using ref to avoid unnecessary copying. // When Bug 2443 is fixed, this may need to change. foreach(ref elem; r) { if(initialized) Bye, bearophile
Mar 06 2012