First class lazy Interval
Daniel Keep
daniel.keep.lists at gmail.com
Fri Feb 27 06:47:30 PST 2009
Denis Koroskin wrote:
> On Fri, 27 Feb 2009 16:44:31 +0300, Andrei Alexandrescu
> <SeeWebsiteForEmail at erdani.org> wrote:
>> I'm having trouble understanding what's wrong with the good old data
>> types and functions.
>>
>> Andrei
>
> The syntax. One may want to reuse 0..100 syntax to generate random number:
> auto x = random(0..100); // gimme a random value in [0, 100)
>
> or check if a value belongs to an interval:
>
> T opIndex(size_t index)
> {
> assert(index in 0.._size);
> // ...
> }
I don't think this should be in the language... it just feels like there
isn't enough use for it. Especially not when you can implement it as a
library.
As proof, I've attached an implementation of an integral interval.
Here's a sample of usage (the program prints this if you run it):
> inter[0, 10] = inter[0, 10]
> inter[0..10] = inter[0, 9]
> inter(0, 10) = inter[1, 9]
[a,b] is inclusive, (a,b) is exclusive and [a..b] is lower inclusive,
upper exclusive (to match slicing syntax).
> inter[0..10] % 2 = inter[0, 8] / 2
> inter[1..10] % 2 = inter[2, 8] / 2
> inter[1..10] / 2 = inter[1, 9] / 2
> 6 in inter[0..10] % 2 = true
> 7 in inter[0..10] % 2 = false
I % a produces an interval of all values n in I which satisfy:
n % a == 0.
I / a produces an interval containing every a'th element of I (including
the first).
> inter[0, 30] / 2 = inter[0, 30] / 2
> (inter[0, 30] / 2).length = 16
> (inter[0, 30] / 2) / 3 = inter[0, 30] / 6
> ((inter[0, 30] / 2) / 3).length = 6
> ((inter[0, 30] / 2) / 3).toArray = [0 6 12 18 24 30]
It should support indexing, slicing and length-ing. It should also
support ranges (can't test it, of course :P).
-- Daniel
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: interval.d
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20090228/c7c1af59/attachment.ksh>
More information about the Digitalmars-d
mailing list