www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Delegates, closures and scope

reply Russel Winder <russel russel.org.uk> writes:
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

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] =3D new Thread ( ( ) { pa=
rtialSum ( 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 =3D i ; threads[i] =3D=
 new Thread ( ( ) { partialSum ( 1 + id * sliceSize , ( id + 1 ) * sliceSiz=
e , 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 =3D i ;
      return ( ) { partialSum ( 1 + id * sliceSize , ( id + 1 ) *
sliceSize , delta ) ; } ;
    }
    threads[i] =3D 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.

--=20
Russel.
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=
=3D=3D
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder ekiga.n=
et
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
Nov 14 2010
parent "Daniel Murphy" <yebblies nospamgmail.com> writes:
"Russel Winder" <russel russel.org.uk> wrote in message 
news:mailman.349.1289736653.21107.digitalmars-d puremagic.com... 
Nov 14 2010