assumeSafeAppend and purity
Jonathan M Davis
jmdavisProg at gmx.com
Mon Feb 6 18:01:11 PST 2012
On Tuesday, February 07, 2012 02:54:40 Vladimir Panteleev wrote:
> On Tuesday, 7 February 2012 at 01:47:12 UTC, Jonathan M Davis
>
> wrote:
> > At present, assumeSafeAppend isn't pure - nor is capacity or
> > reserve. AFAIK, none of them access any global variables aside
> > from GC-related stuff (and new is already allowed in pure
> > functions). All it would take to make them pure is to mark the
> > declarations for the C functions that they call pure (and those
> > functions aren't part of the public API) and then mark them as
> > pure. Is there any reason why this would be a _bad_ idea?
>
> pure void f(const(int)[] arr)
> {
> debug /* bypass purity check to pretend assumeSafeAppend is pure
> */
> {
> assumeSafeAppend(arr);
> }
> arr ~= 42;
> }
>
> void main()
> {
> int[] arr = [0, 1, 2, 3, 4];
> f(arr[1..$-1]);
> assert(arr[4] == 4, "f has a side effect");
> }
Except that assumeSafeAppend was misused. It's dangerous to use when you don't
use it properly regardless of purity. By its very nature, it can screw stuff
up. The problem is what to do when you use it _correctly_ and want to use it
in a pure function? If used properly, aside from avoiding potential
reallocations, assumeSafeAppend has no effect. Should it be made pure, because
as long as you're using it properly it's not a problem (and it's always a
problem if you misuse it - regardless of purity)? Or should the caller be
forced to cast it to pure to use it in a pure function?
Given how ugly having to deal with the casting is and the fact that misusing
assumeSafeAppend results in very broken code anyway, I'd be inclined to just
mark it as pure.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list