D const design rationale
Reiner Pope
some at address.com
Sun Jun 24 06:34:46 PDT 2007
Bill Baxter wrote:
> Don Clugston wrote:
>> Walter Bright wrote:
>
>>> You can't do that with C/C++ because arrays can be aliased. I have a
>>> stack of papers 6" deep in the basement on trying to make C more
>>> suitable for numerics, and it's mostly about, you guessed it, fixing
>>> the alias problem. They failed.
>>
>> How much of this will actually be solved by invariant?
>> It seems to me that typically, arrays are built up element-by-element,
>> even if they never change again. I guess in D2.0, such code would
>> initialize a temporary array, and finally idup it?
>>
>> The aliasing problem will be far from gone, though. Consider an
>> in-place operation on a matrix. Frequently you modify one only row at
>> a time, based on the remaining rows. I think you'd have to
>> cast(invariant) those other rows, to avoid aliasing.
>
> Thanks for asking this. It's been eating at me too. From what I
> understand of Fortran code, you declare an array of a given size, set
> its values however you like, then pass it to a function. But if we make
> an invariant D array we can't set its values after initialization. So
> it doesn't seem very useful. Or is the use pattern going to be, as you
> say, Don, casting to invariant every time you need to call
> fast_math_array_function()? If that's the case I suspect it won't take
> long before this becomes an idiom:
>
> /* x += y array-style */
> add_accum(double[] x, const double[] y) {
> _add_accum_impl(cast(invariant)x,cast(invariant)y);
> }
>
> Is that really what we want?
> That code can't even be right though, because x is *supposed* to get
> modified there. So how do you denote lack of aliasing on something like
> that using invariant? In this respect C99's 'restrict' seems to be a
> lot more understandable. My naive understanding of it being that you
> just slap it on any argument that you want to tell the compiler it can
> assume to be non-aliased.
>
> --bb
Functional languages don't entirely solve the aliasing problem, because
keeping everything immutable means arrays would need to be copied all
over the place. Clean has uniqueness types, which allow the type system
to specify that your pointer is the only one to that data. I don't know
how they work, but maybe they could be an appropriate solution? (Not to
mention that they've been proposed before to avoid the cast-to-invariant
after creating new data)
Much of the enforcement work, I think, could be done by scope (because
it tells you that functions you call won't keep a pointer to your data).
After that, it might give you 'restrict', but actually type-checked, and
basically for free.
(But that's only a guess)
Reiner
More information about the Digitalmars-d
mailing list