Delegates, closures and scope

Russel Winder russel at russel.org.uk
Sun Nov 14 04:12:24 PST 2010


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 at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at russel.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20101114/0b7a9e5f/attachment.pgp>


More information about the Digitalmars-d mailing list