Unofficial wish list status.(Mar 2009)

Daniel Keep daniel.keep.lists at gmail.com
Sun Mar 1 00:25:10 PST 2009



Tim M wrote:
> Through out that page it shows examples of iterations where order is not
> actually defined, the index has to modify by one but it gives the
> compiler the ability to create a few threads and execute in parallel.
> Thats what I was actually talking about. I would hate for that code to
> be valid and would prefer to use the usual while, do while, for and
> foreach loops but have an attribute to enable optimization eg:
> 
> unordered for(i = 0; i < 10; ++i)
> {
>    //anything here is independant of the previous iterations
>    //and I dont care if compiler splits accross cpu cores
> }
> 
> Anyway I still think there is of low priority over other things like
> cent data type but it is rated rather high.

C-style for is a pretty terrible construct for this.  How can it be
unordered when you've SPECIFIED that i increases linearly?

Does that mean it's equivalent to this?

unordered for(i = 9; i >= 0; --i)
{
    ...
}

If so, then 60% of that statement is redundant.  So let's try using
foreach instead.

unordered foreach( i ; 0..10 )
{
    ...
}

Much better.  But now the compiler has to prove that it's actually
possible to run this in arbitrary order.  The easiest way to do this is
to check to see whether the body of the foreach is pure or not.  Problem
there is that it CAN'T be pure; if it's pure, then the loop cannot
produce any results.

I think we have a better chance in stealing ideas from the functional
world like parallel map, or map-reduce.

> pure int mutate(int x)
> {
>     // some long calculation which mutates x
>     return x;
> }
>
> pure int combine(int a, int b)
> {
>     // some long calculation which mutates a and b
>     return a + b;
> }
>
> auto results = pmap!(mutate)(inter[0..10]);
>
> // or...
>
> auto result = mapreduce!(mutate, combine)(inter[0..10]);

Because we've relinquished direct control over iteration and our
functions are pure, the compiler is free to rewrite both those last two
statements any way it pleases.  It could distribute the workload across
hardware threads, or even distribute it across machines; it doesn't matter.

Another potential way of doing this would be to make the following valid:

auto results = foreach( i ; 0..10 )
{
    ...
    continue 2*i;
}

Assuming the body of the foreach is pure, that might work.  How you'd
write a reduce with a loop, I have no idea.  :P

The nice thing about using functional constructs is that they're just
functions; they can be implemented in a library without having to touch
the language itself.

  -- Daniel



More information about the Digitalmars-d mailing list