Compartilhar via


Factorial in VB 9.0 using closures.

You cannot declare a closure directly in VB right now, however in the last CTP verion of VB 9.0 you can create some closures indirectly using quries syntax.

The following is by no means is an effective implementation of factorial function :-) , but it should be an interesting use case of closures.

 

Module Module1

    Sub Main()

        'create a closure

        Dim factorial_closure = fac(10)

        'get result (most of the calculations will happen here)

        Dim result = factorial_closure(0)

        Console.WriteLine(result)

    End Sub

    Function fac(ByVal x As Integer) As IEnumerable(Of Integer)

        ' this function roughly means this:

        'fun fac 0 = 1

        ' | fac n = n * fac(n-1);

        If x = 0 Then Return {1}

        Return From dummy In {Nothing} _

            Select x * fac(x - 1)(0)

    End Function

End Module