Ideas from the Chapel language (swap)

Bruce Adams tortoise_74 at yeah.who.co.uk
Wed Oct 3 17:59:37 PDT 2007


Derek Parnell Wrote:

> On Wed, 03 Oct 2007 14:53:57 -0400, Bruce Adams wrote:
> 
> > bearophile Wrote:
> > 
> >> The Cray Inc is designing the Chapel Language:
> >> http://chapel.cs.washington.edu/
> >> The following notes are from the specification V. 0.750:
> >> http://chapel.cs.washington.edu/spec-0.750.pdf
> >> I think it's rather cute, it looks like a cross between C++, Fortress and Python. Here are few things I think can be interesting for D designers too:
> >> 
> >> - Chap. 11.5 page 65, swap operator (useful but probably not enough to justify a new operator)
> > 
> > swap is very useful especially in exception safe programming.
> > I would like to see swap used as the default implementation of D's transfer constructor (and C++0x's forthcoming move constructor)
> 
> Isn't a simple template such this sufficient?
> 
> template swap(TYPE)
> {
>     void swap(ref TYPE a, ref TYPE b)
>     {
>         synchronized
>         {
>           TYPE temp = a;
>           a = b;
>           b = temp;
>         }
>     }
> 
> }
> 
> 
> -- 
> Derek Parnell
> Melbourne, Australia
> skype: derek.j.parnell

Most of the time it is.
Sometimes swapping references is sufficient but sometimes you actually
want real data to change. As the type gets bigger you start
to prefer decomposing swap into swaps of individual members rather than 2 whole copes. Do you really want to copy 120Mb twice?
Actually you should decomposing the swap from the outset if possible
(second to swapping just references if possible obviously).
Swaps also have to be atomic and never throw exceptions.
A more advanced template might use tuples recursively to do this.
I would want that in the standard library.

Some hardware platforms may support swaps directly. In reversible computing (okay so no-one in the real world uses that - yet) it is a fundamental operation. Then it becomes a compiler decision how best to implement it. If it is used as the default implementation for transfer constructors this goes double. 
I suspect a standard library implementation is sufficient from the outset
leaving it up to the compiler vendor to decide how clever he or she needs to be.

It continues to suprise me that we don't prefer swap to destructive assignment more generally. Perhaps it feels less natural after years of the C way?

Bruce.




More information about the Digitalmars-d mailing list