Using map instead of iteration

Simen kjaeraas simen.kjaras at gmail.com
Sun Mar 6 05:57:12 PST 2011


Russel Winder <russel at russel.org.uk> wrote:

> I have a code fragment:
>
>   auto threads = new Thread[numberOfThreads] ;
>   foreach ( i ; 0 .. numberOfThreads ) {
>     void delegate ( ) closedPartialSum ( ) {
>       immutable id = i ;
>       return ( ) { partialSum ( id , sliceSize , delta ) ; } ;
>     }
>     threads[i] = new Thread ( closedPartialSum ) ;
>   }
>
> which clearly should be doable using map from std.algorithm.  So I
> tried:
>
>   auto threads = map ! ( function Thread ( int i ) {
>       void delegate ( ) closedPartialSum ( ) {
>         immutable id = i ;
>         return ( ) { partialSum ( id , sliceSize , delta ) ; } ;
>       }
>       return new Thread ( closedPartialSum ) ;
>     } ) ( 0 .. numberOfThreads )
>
> which fails:
>
> pi_d2_threadsGlobalState.d(41): found '..' when expecting ','
> pi_d2_threadsGlobalState.d(57): semicolon expected following auto
> declaration, not 'foreach'
>
> So clearly 0 .. numberOfThreads only means a range of integers in a
> foreach or array index only and not everywhere as it does in all
> sensible languages :-((
>
> I am clearly missing something, anyone any ideas?

You should use std.range.iota(0,numberOfThreads) instead of
0..numberOfThreads. Having a..b return a general interval range
has been proposed numerous times, but nothing has been implemented as
of yet.

If you like syntactic sugar, this is likely the closest you'll get at
this point:

import std.range;

struct _ {
     auto opSlice(B,E)(B begin, E end) {
         return iota(begin, end);
     }
}

// Example:
map!foo( _[0..numberOfThreads] );

-- 
Simen


More information about the Digitalmars-d mailing list