View mode: basic / threaded / horizontal-split · Log in · Help
November 14, 2010
Delegates, closures and scope
I wonder if the following is just a misunderstanding on my part or an
indicator of an actual problem in D.

The code:

foreach ( i ; 0 .. numberOfThreads ) { threads[i] = new Thread ( ( ) { partialSum ( 1 + i * sliceSize , ( i + 1 ) * sliceSize , delta ) ; } ) ; }

fails to the intended thing, i.e. I had assumed that the created
delegates were in fact closures.  However it seems that a delegate
simply has a reference to the scope in which it was defined, it doesn't
capture the environment.  This means the value of i and sliceSize are
always the value when the function is executed not when it is created.
I even tried:

foreach ( i ; 0 .. numberOfThreads ) { immutable id = i ; threads[i] = new Thread ( ( ) { partialSum ( 1 + id * sliceSize , ( id + 1 ) * sliceSize , delta ) ; } ) ; }

and this behaves strangely differently, but it still doesn't work as
required, it is still not creating closures.   All the created delegates
still share a reference to the same scope.  By trial and error I came up
with:

foreach ( i ; 0 .. numberOfThreads ) {
   void delegate ( ) closedPartialSum ( ) {
     immutable id = i ;
     return ( ) { partialSum ( 1 + id * sliceSize , ( id + 1 ) *
sliceSize , delta ) ; } ;
   }
   threads[i] = new Thread ( closedPartialSum ) ;
 }

and this seems to do the right thing, but this seems like a strange hoop
to jump through to create closures.

I guess my question is whether there is any need for delegates that are
not closures?  Wouldn't it be simpler to do lexical closures as the only
form of delegate?

BTW This is not a problem particular to D, Python has similar issues
where Scala, Clojure, Ruby do not.  Groovy is very weird in that what it
calls a closure is actually just a code block.

-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder@ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel@russel.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder
November 15, 2010
Re: Delegates, closures and scope
"Russel Winder" <russel@russel.org.uk> wrote in message 
news:mailman.349.1289736653.21107.digitalmars-d@puremagic.com...
Top | Discussion index | About this forum | D home