ints(), longs(), doubles() <was> Re: Ranges
Howard Lovatt
howard.lovatt at gmail.com
Fri May 3 18:45:12 PDT 2013
I write numerical code and find something like:
from(start).to(exclusiveEnd).step(step).stream()...
with generalised to (whileTrue) and step variations, e.g.:
from(start).whileTrue((i) -> i < limit).step((i) -> 2 * i).stream()...
useful in my in house library, it's great for paralleling existing loops!
I implement it with something like this (I am using an in-house stream library so below is para-phrasing what I do):
public interface IntStream {
...
class Range {
private int from = 0;
private IntPredicate whileTrue = (notUsed) -> true;
private IntFunction step = (i) -> i + 1;
public Range from(int from) { this.from = from; return this; }
public Range to(int exclusiveEnd) { whileTrue = (i) -> i < exclusiveEnd; return this; }
public Range step(int step) { this.step = (i) -> i + 1; return this; }
public Range step(IntFunction step) { this.step = step; return this; }
public Range whileTrue(IntPredicate whileTrue) { this.whileTrue = whileTrue; return this; }
public IntStream stream() { ... }
}
static Range from(int from) { return new Range().from(from); }
static Range to(int exclusiveEnd) { return new Range().to(exclusiveEnd); }
static Range step(int step) { return new Range().step(step); }
static Range step(IntFunction step) { return new Range().step(step); }
static Range whileTrue(IntPredicate whileTrue) { return new Range().whileTrue(whileTrue); }
static IntStream stream() { return new Range().stream(); }
}
-- Howard.
Sent from my iPad
On 04/05/2013, at 3:35 AM, Tim Peierls <tim at peierls.net> wrote:
> On Fri, May 3, 2013 at 1:26 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>
>> I don't think it would. While "indexes" does capture the essence of a
>>> common use of this method, I think of [start, bound) as a range, and
>>> would look it up under that name. range and rangeClosed are very similar
>>> concepts; they should have similar names. The potential for confusion
>>> doesn't seem that significant to me.
>>>
>>
>> With two forms, I agree. But the next two questions are:
>> - what about decreasing ranges?
>> - what about decreasing closed/half-open ranges (whichever the above
>> isnt)?
>>
>> Now, if the answer to these incremental questions is "you lose", then
>> range and rangeClosed are fine, and we're done.
>>
>
> All of these variations seem like things that aren't hard to roll for
> yourself, especially with a few good examples in the javadoc.
>
> But if range and rangeClosed really don't feel like enough to you, then
> retain the stepped versions (with a different, uglier name) but add an
> open/closed argument so it's only one extra method for each of the
> primitive types and not two.
>
> rangeFarAfield(start, bound, step, HALF_OPEN);
>
> Ugly enough that people won't use it unless they have to.
>
> --tim
More information about the lambda-dev
mailing list