Results 1 to 12 of 12

Thread: Question about Lamda Expression

Threaded View

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Oct 2007
    Posts
    544

    Question about Lamda Expression

    vb.net Code:
    1. Sub Test()
    2.     Dim y As Integer = 10
    3.     Dim Lambda As Func(Of Integer, Integer) = Function(ByVal x) x + y
    4.     y = 20
    5.     Console.WriteLine(Lambda(5))
    6. End Sub

    So the method vb.net use to generate lamda expression is similar to C++ functor.

    So far so good.

    What value is displayed when you execute this function? If you said 25, you were spot on. Why 25? Well, the compiler captures and rewrites all of the free variables y to the closure's copy, like so:
    vb.net Code:
    1. Sub Test()
    2.     Dim Closure As New $CLOSURE_Compiler_Generated_Name$
    3.     Closure.y = 10
    4.     Dim Lambda = AddressOf Closure.Lambda_1
    5.     Closure.y = 20
    6.     Console.WriteLine(Lambda(5))
    7. End Function
    I still do not understand why Microsoft decide to change the second y=20 into closure.y=20?

    The first closure.y=10 make sense. In fact, if I were microsoft, a more normal way to generate the code will be to have a variable would be to do

    vb.net Code:
    1. Sub Test()
    2.     Dim Closure As New $CLOSURE_Compiler_Generated_Name$
    3.     y=10
    4.     Closure.y = y
    5.     Dim Lambda = AddressOf Closure.Lambda_1
    6.     'Closure.y = 20 Remove this line.
    7.     Console.WriteLine(Lambda(5))
    8. End Function

    Why Microsoft do it the microsoft way instead of the way that make more sense? The microsoft way is when y change value then the Lambda variable also change. It becomes a different function. Also what are the rules where microsoft will change y=10 into Closure.y=10?



    vb.net Code:
    1. Sub Test()
    2.     For I = 1 To 5
    3.         StartThread(Function() I + 10)
    4.     Next
    5. End Function

    Won't work properly because I keeps changing. What I think would happen is that thread may actually be started sometimes latter, say during doevents or latter.

    At that time I would have became 5 or 6 and all threads will simply print 15. Wouldn't happen if Microsoft do things the normal my way.

    http://msdn.microsoft.com/en-us/magazine/cc163362.aspx
    vb.net Code:
    1. Sub Test()
    2.     For I = 1 To 5
    3.         Dim x = I
    4.         StartThread(Function() x + 10)
    5.     Next
    6. End Function

    How the hell doing Dim x=i change anything?

    Microsoft compiler change all occurrence of I=1,2,3,4,5 into Closure.I=1,2,3,4,5

    Why microsoft don't do the same for x?
    Last edited by teguh123; Mar 2nd, 2011 at 02:57 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width