Functional Style Programming with C#

by Miguel de Icaza

C# 3.0 introduces a number of small enhancements to the language. The combination of these enhancements is what drives the LINQ.

Although much of the focus has been on the SQL-like feeling that it gives the language to manipulate collections, XML and databases in an efficient way, some fascinating side effects are explored in this tutorial.

The tutorial introduces the new features in C# one by one, there are a couple of interesting examples, a simple functional-style loop:

// From:
for (int i = 1; i < 10; ++i) Console.WriteLine(i);

// To:
Sequence.Range(1, 10).ForEach(i => Console.WriteLine(i));

A nice introduction to delayed evaluation, an RPN calculator:

// the following computes (5*2)-1
Token[] tkns = {
    new Token(5),
    new Token(2),
    new Token(TokenType.Multiply),
    new Token(1),
    new Token(TokenType.Subtract)

Stack st = new Stack();

// The RPN Token Processor
    i => (int)i.Type,
    s => st.Push(s.Operand),
    s => st.Push(st.Pop() + st.Pop()),
    s => st.Push(-st.Pop() + st.Pop()),
    s => st.Push(st.Pop() * st.Pop()),
    s => st.Push(1/st.Pop() * st.Pop())


And finally a section on how to parse WordML using LINQ, extracting the text:

	wordDoc.Element(w + "body").Descendants(w + "p").
		Select(p => new {
        		ParagraphNode = p,
        		Style = GetParagraphStyle(p),
        		ParaText = p.Elements(w + "r").Elements(w + "t").
				Aggregate("", (s1, i1) => s1 = s1 + (string)i1)}).
		Foreach(p =>
			 Console.WriteLine("{0} {1}", p.Style.PadRight(12), p.ParaText));

Very educational read.

Posted on 10 Jan 2007