sum of numbers using Primitives range

Stephen Colebourne scolebourne at joda.org
Wed Dec 12 00:58:35 PST 2012


I suspect there may be some previous expectation about integer ranges
being inclusive. Just looking at that code, that is what I would have
presumed.

Sadly, Groovy's documentation is unclear
http://groovy.codehaus.org/api/groovy/lang/IntRange.html

While Guava requires the user to choose
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Range.html

At the very least I think that this signature (with no Javadoc)
 public static IntStream range(final int from, final int upTo)
would be better as
 public static IntStream range(final int startInclusive, final int endExclusive)

As a side note, this is a problem with JSR-310 too. Users generally
want date ranges to be inclusive of the end (from Tue to Thu means 3
whole days, but time ranges are exclusive of the end (from 9am to 5pm,
generally means you shouldn't expect to accept 5pm). (310 does not
currently have ranges in part because of this)

Stephen


On 12 December 2012 02:10, Arul Dhesiaseelan <aruld at acm.org> wrote:
> My bad, I was assuming inclusive. Thanks Brian.
>
>
> On Tue, Dec 11, 2012 at 3:55 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>
>> 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45.  Ranges are half-open.  As in,
>>
>>   for (int i=0; i<10; i++) { ... }
>>
>>
>>
>>
>> On 12/11/2012 8:46 PM, Arul Dhesiaseelan wrote:
>>
>>> Sum of integers over using a Primitives range returns invalid result.
>>>
>>>      range(1, 10).map(operand -> operand).sum();
>>>      range(1, 10).reduce(0, Integer::sum);
>>>      range(1, 10).sum();
>>>
>>>
>>> They all yield 45, instead of 55. Is this a bug?
>>>
>>> -Arul
>>>
>>>
>


More information about the lambda-dev mailing list