Why are there Properties in D?
Marc Schütz" <schuetzm at gmx.net>
Marc Schütz" <schuetzm at gmx.net>
Fri Feb 14 11:24:57 PST 2014
On Friday, 14 February 2014 at 16:16:28 UTC, Robin wrote:
> On Friday, 14 February 2014 at 15:21:04 UTC, Jesse Phillips
> wrote:
>> FYI an infinite range is defined to have
>>
>> struct Infinite {
>> enum empty = false;
>> }
>>
>> You know it will never be empty at compile time.
>
> Hiho,
>
> thank you for this interesting input. =)
>
> Couldn't this be equally possible (also at runtime) with the
> following:
>
> struct Infinite {
> enum empty_ = false;
> bool empty() pure { return empty_; }
> }
Yes, but only at runtime. For some things to work, you need to be
able to know it at compile time. `std.range` defines a template
`isInfinite` that checks for this.
This information can be used for some optimizations:
`std.algorithm.count` and `std.range.walkLength` are only defined
for non-infinite ranges (to avoid creating an infinite loop),
`std.algorithm.cartesianProduct` can work with two infinite
ranges using a special enumeration strategy if it can detect
them, `std.range.chain` can optimize index access by stopping at
the first infinite range, `std.range.take` can always define a
length for infinite ranges (even if they don't have a length
property themselves), ...
Another example: The `length` property of ranges. It is possible
to turn builtin slices (dynamic arrays) into ranges by importing
`std.range` or `std.array`. Slices already have a member field
`length` by default. Here you have an example where it's
impossible to define a method `length()`. With properties,
nothing special needs to be done: You can always use `length`
without parens, even if it happens to be a method.
More information about the Digitalmars-d
mailing list