Monday, August 27, 2007 12:00 AM bart

Visual Basic 9.0 Feature Focus - Lambda Expressions

Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Lambda Expressions, a feature also available in C# 3.0 (see here). So, what's this feature called after a Greek letter? Lambda expressions are derived from the domain of functional programming, or in a broader sense from lambda calculus (as introduced by A. Church back in the 30s). The lambda calculus is used to define and study (computable) functions. As an example, consider the lambda definition below:

λab.a + b

which represents a function with two inputs a and b, producing a + b as its result. So, the following equals to 5:

(λab.a + b) 2 3

Enough basic theory for now, what's the use of all this in VB 9.0 (and C# 3.0). Well, consider the following example of a simple "flexible calculator" in VB 8.0:

Delegate Function Func(Of A, B, R)(ByVal a As A, ByVal b As B)

Module Calculator

    Function Calc(ByVal f As Func(Of Integer, Integer, Integer), ByVal a As Integer, ByVal b As Integer) As Integer
        Return f(a, b)
    End Function

End Module

It's flexible because the Calc method can take in a delegate to a function in order to do the real calculation. To do this, we've defined a generic delegate called Func that has two inputs, typed A and B, and an output typed R. In order to call this method, you'll have to provide a reference to a method with the right signature, like this:

Module Demo

    Function Add(ByVal a As Integer, ByVal b As Integer) As Integer
        Return a + b
    End Function

    Sub Main()
        Dim res = Calculcator.Calc(AddressOf Add, 1, 2)
    End Sub

End Module

Quite a bit of work just to call the Calc method, isn't it? What if we could write the Add function inline with the Calc call? That's exactly what lambda expressions allow you to do in VB 9.0:

Module Demo

    Sub Main()
        Dim res = Calculcator.Calc(Function(a, b) a + b, 1, 2)
    End Sub

End Module

Behind the scenes, the compiler will cook up an anonymous method that captures the lambda function (e.g. _Lambda$__1), which is equivalent to the manual approach one had to take in VB 8.0. As you can see, the compiler is smart enough to figure out the types expected for the lambda expression parameters, so you don't need to specify those (although you could if you really want to do so).

Lambdas are used extensively in LINQ queries, which are by nature pretty functional. After all, a query predicate (the "result filter") is a condition that takes in an object from the query source and produces a boolean. In other words, such a predicate is nothing more than a function of type Func(Of SourceType, Boolean). In a similar way, a query projection is a function that takes in an object from its source and produces another object (possibly an anonymous type). To illustrate this, consider a simple LINQ query (which we'll talk about in much more detail in a future post):

Dim res = From p In products Where p.Price > 100 Select New With { .Name = p.ProductName, p.Price }

This gets translated (lexically) into the following using extension methods and lambdas:

Dim res = products.Where(Function(p) p.Price > 100).Select(Function(p) New With { .Name = p.ProductName, p.Price })

Notice I can't tell the type of the res variable (I'm looking Implicitly Typed Local Variables), in this case it's something like IEnumerable(Of AnonymousTypeOfTheProjection) - strictly spoken it can be an IQueryable(Of ...) too, which I'll discuss in subsequent posts.

Lambdas can be used for expressions only, you can't embed statements in a lambda's body (like Console.WriteLine): lambda functions take in some data and produce other data, that's it. As an exercise, predict the output of the following:

Console.WriteLine((Function(a, b) a + b)(1, (Function(c, d) c * d)(2, 3)))

In lambda calculus terms, this comes down to a technique called "ß-reduction".

Happy coding!

Del.icio.us | Digg It | Technorati | Blinklist | Furl | reddit | DotNetKicks

Filed under:

Comments

# 15 Links Today (2007-08-27)

Monday, August 27, 2007 8:19 AM by 15 Links Today (2007-08-27)

Pingback from  15 Links Today (2007-08-27)

# University Update-So You Think You Can Dance-Visual Basic 9.0 Feature Focus - Lambda Expressions

Pingback from  University Update-So You Think You Can Dance-Visual Basic 9.0 Feature Focus - Lambda Expressions

# VB 9.0 Feature Focus

Wednesday, September 05, 2007 6:50 PM by Nick's .NET Travels

In my previous post I commented that VB is coming of age in Visual Studio 2008 with better support for

# MSDN Blog Postings » New Features of Visual Basic 9 Article Series

Pingback from  MSDN Blog Postings  » New Features of Visual Basic 9 Article Series

# New Features of Visual Basic 9 Article Series

Thursday, September 27, 2007 5:47 AM by Walter Stiers - Academic Relations Team (BeLux)

In a series of 15 posts, Bart De Smet explores several of the new features in Visual Basic 9 . These

# http://bartdesmet.net/blogs/bart/archive/2007/08/27/visual-basic-9-0-feature-focus-lambda-expressions.aspx

# VB 9.0 Feature Focus – Link Collection

Saturday, August 09, 2008 7:16 AM by B# .NET Blog

Collecting a few of my posts for easy quick reference: Visual Basic 9.0 Feature Focus – Introduction