Changeset 1947

Show
Ignore:
Timestamp:
08/30/10 19:09:39 (1 year ago)
Author:
dsimcha
Message:

std.algorithm.reduce() should throw on empty ranges and no explicit seed instead of silently returning bogus results.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • trunk/phobos/std/algorithm.d

    r1946 r1947  
    421421            else 
    422422            { 
     423                enforce(!args[$ - 1].empty, 
     424                    "Cannot reduce an empty range w/o an explicit seed value."); 
    423425                alias args[0] r; 
    424426                static if (fun.length == 1) 
     
    505507            } 
    506508 
     509            enforce(initialized, 
     510                "Cannot reduce an empty iterable w/o an explicit seed value."); 
     511 
    507512            static if(fun.length == 1) 
    508513            { 
     
    545550    struct OpApply 
    546551    { 
     552        bool actEmpty; 
     553 
    547554        int opApply(int delegate(ref int) dg) 
    548555        { 
    549556            int res; 
     557            if(actEmpty) return res; 
     558 
    550559            foreach(i; 0..100) 
    551560            { 
     
    563572    assert(reduce!("a + b", max)(oa) == tuple(hundredSum, 99)); 
    564573    assert(reduce!("a + b", max)(tuple(5, 0), oa) == tuple(hundredSum + 5, 99)); 
     574 
     575    // Test for throwing on empty range plus no seed. 
     576    try { 
     577        reduce!"a + b"([1, 2][0..0]); 
     578        assert(0); 
     579    } catch(Exception) {} 
     580 
     581    oa.actEmpty = true; 
     582    try { 
     583        reduce!"a + b"(oa); 
     584        assert(0); 
     585    } catch(Exception) {} 
    565586} 
    566587