Weird issue with std.range.iota.length

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 12 09:58:28 PST 2016


On Fri, Feb 12, 2016 at 05:38:40PM +0000, Jonathan M Davis via Digitalmars-d wrote:
> On Friday, 12 February 2016 at 16:52:17 UTC, ixid wrote:
> >On Friday, 12 February 2016 at 15:59:09 UTC, Jonathan M Davis wrote:
> >>It would be far better IMHO to just do a check in iota and throw a
> >>RangeError if the length wouldn't fit in size_t. Having length ever
> >>be anything other than size_t is just going to cause problems with
> >>other ranges. On 32-bit systems, you lose out on the ability to have
> >>a range that covers all values of long or ulong, but that's of very
> >>limited usefulness anyway, and as long as the number of elements is
> >>no greater than size_t.max, it would be fine - which would cover
> >>virtually all use cases. No, it's not perfect, but allowing length
> >>to be anything but size_t just causes bugs - especially in generic
> >>code.
> >>
> >>- Jonathan M Davis
> >
> >What about a template overload where you can set the length type as
> >separate from the type of the range elements?
> 
> No other range has anything but size_t for its length. It's what
> arrays use.  It's what the container types use. Code in general is
> going to assume that length is size_t. I think that having any range
> types with a length type of anything but size_t is a mistake. It
> interacts badly with everything else.  The post that started this
> thread is just one example of that.
[...]

IMO, fixing a specific type for length is a mistake.  Truly generic code
should treat the length as an opaque type (possibly satisfying some
constraints, like <-comparable, ==-comparable, and maybe supporting
basic arithmetic operations), and should use generic templates like
CommonType!(...) if it needs to work with multiple length types.

Restricting length to size_t or ulong or whatever, is an arbitrary
restriction on ranges, because conceptually you can have ranges whose
length exceeds the size of all native integral types (e.g., BigInt
lengths), but certain length computations may still make sense, and the
range is still usable as long as you only ever operate on a small
segment of it.

Of course, working with an opaque length type makes it harder to write
correct code, but such is the price of generic programming.


T

-- 
Debian GNU/Linux: Cray on your desktop.


More information about the Digitalmars-d mailing list