# functional programming

This little script uses the JQuery getScript command, enforcing sequential loading order to ensure script dependencies are honoured:

 function LoadScriptsSequentially(scriptUrls, callback) { if (typeof scriptUrls == 'undefined') throw "Argument Error: URL array is unusable"; if (scriptUrls.length == 0 && typeof callback == 'function') callback(); \$.getScript(scriptUrls.shift(), function() { LoadScriptsSequentially(scriptUrls, callback); }); } 

Here’s how you use it:

 function InitialiseQueryFramework(runTests) { LoadScriptsSequentially([ "/js/inheritance.js", "/js/expressions.js", "/js/refData.js", "/js/queryRenderer.js", "/js/sha1.js", "/js/queryCache.js", "/js/unit-tests.js"], function() { queryFramework = new QueryManager("#query"); if (runTests) RunTestSuite(); }); } 

I love javascript now and can’t understand why I avoided it for years. I particularly love the hybrid fusion of functional and procedural paradigms that possible in JS. You can see that at work in the parameters being passed into the recursive call to LoadScriptsSequentially.

What do you think? Is there a better/nicer way to do this?

# PostSharp Laos – Beautiful AOP.

I’ve recently been using PostSharp 1.5 (Laos) to implement various features such as logging, tracing, API performance counter recording, and repeatability on the softphone app I’ve been developing. Previously, we’d been either using hand-rolled code generation systems to augment the APIs with IDisposable-style wrappers, or hand coded the wrappers within the implementation code. The problem was that by the time we’d added all of the above, there were hundreds of lines of code to maintain around the few lines of code that actually provided a business benefit.

Several years ago, when I worked for Avanade, I worked on a very large scale project that used the Avanade Connected Architecture (ACA.NET) – a proprietary competitor for PostSharp. We found Aspect Oriented Programming (AOP) to be a great way to focus on the job at hand and reliably dot all the ‘i’s and cross all the ‘t’s in a single step at a later date.

ACA.NET, at that time, used a precursor of the P&P Configuration Application Block and performed a form of post build step to create external wrappers that instantiated the aspect call chain prior to invoking your service method. That was a very neat step that could allow configurable specifications of applicable aspects. It allowed us to develop the code in a very naive in-proc way, and then augment the code with top level exception handlers, transactionality etc at the same time that we changed the physical deployment architecture. Since that time, I’ve missed the lack of such a tool, so it was a pleasure to finally acquaint myself  with PostSharp.

I’d always been intending to introduce PostSharp here, but I’d just never had time to do it. Well, I finally found the time in recent weeks and was able to do that most gratifying thing – remove and simplify code, improve performance and code quality, reduced maintenance costs and increased the ease with I introduce new code policies all in a single step. And all without even scratching the surface of what PostSharp is capable of.

Here’s a little example of the power of AOP using PostSharp, inspired by Elevate’s memoize extension method. We try to distinguish as many of our APIs as possible into Pure and Impure. Those that are impure get database locks, retry handlers etc. Those that are pure in a functional sense can be cached, or memoized. Those that are not pure in a functional sense are those that while not saving any data still are not one-to-one between arguments and result, sadly that’s most of mine (it’s a distributed event driven app).

[Serializable]
public class PureAttribute : OnMethodInvocationAspect
{
Dictionary<int, object> PreviousResults = new Dictionary<int, object>();

public override void OnInvocation(MethodInvocationEventArgs eventArgs)
{
int hashcode = GetArgumentArrayHashcode(eventArgs.Method, eventArgs.GetArgumentArray());
if (PreviousResults.ContainsKey(hashcode))
eventArgs.ReturnValue = PreviousResults[hashcode];
else
{
eventArgs.Proceed();
PreviousResults[hashcode] = eventArgs.ReturnValue;
}
}

public int GetArgumentArrayHashcode(MethodInfo method, params object[] args)
{
StringBuilder result = new StringBuilder(method.GetHashCode().ToString());

foreach (object item in args)
result.Append(item);
return result.ToString().GetHashCode();
}
}

I love what I achieved here, not least for the fact that it took me no more than about 20 lines of code to do it. But that’s not the real killer feature, for me. It’s the fact that PostSharp Laos has MulticastAttributes, that allow me to apply the advice to numerous methods in a single instruction, or even numerous classes or even every method of every class of an assembly. I can specify what to attach the aspects to by using regular expressions, or wildcards. Here’s an example that applies an aspect to all public methods in class MyServiceClass.

[assembly: Pure(
AspectPriority = 2,
AttributeTargetAssemblies = "MyAssembly",
AttributeTargetMemberAttributes = MulticastAttributes.Public,
AttributeTargetMembers = "*")]

Here’s an example that uses a wildcard to NOT apply the aspect to those methods that end in “Impl”.

[assembly: Pure(
AspectPriority = 2,
AttributeTargetAssemblies = "MyAssembly",
AttributeTargetMemberAttributes = MulticastAttributes.Public,
AttributeExclude = true,
AttributeTargetMembers = "*Impl")]

Do you use AOP? What aspects do you use, other than the usual suspects above?

# State Machines in C# 3.0 using T4 Templates

UPDATE: The original code for this post, that used to be available via a link on this page, is no longer available. I’m afraid that if you want to try this one out, you’ll have to piece it together using the snippets contained in this post. Sorry for the inconvenience – blame it on ISP churn.

Some time back I wrote about techniques for implementing non-deterministic finite automata (NDFAs) using some of the new features of C# 3.0. Recently I’ve had a need to revisit that work to provide a client with a means to generate a bunch of really complex state machines in a lightweight, extensible and easily understood model. VS 2008 and C# 3.0 are pretty much the perfect platform for the job – they combine partial classes and methods, lambda functions and T4 templates making it a total walk in the park. This post will look at the prototype system I put together. This is a very code intensive post – sorry about that, but it’s late and apparently my eyes are very red, puffy and panda like.

State machines are the core of many applications – yet we often find people hand coding them with nested switch statements and grizzly mixtures of state control and business logic. It’s a nightmare scenario making code completely unmaintainable for anything but the most trivial applications.

The key objective for a dedicated application framework that manages a state machine is to provide a clean way to break out the code that manages the state machine from the code that implements the activities performed as part of the state machine. C# 3.0 has a nice solution for this – partial types and methods.

### Partial types and methods

A partial type is a type whose definition is not confined to a single code module – it can have multiple modules. Some of those can be written by you, others can be written by a code generator. Here’s an example of a partial class definition:

public partial class MyPartialClass{}

By by declaring the class to be partial, you say that other files may contain parts of the class definition. the point of this kind of structure is that you might have piece of code that you want to write by hand, and others that you want to have driven from a code generator, stuff that gets overwritten every time the generator runs. If your code got erased every time you ran the generator, you’d get bored very quickly. You need a way to chop out the bits that don’t change. Typically, these will be framework or infrastructure stuff.

Partial classes can also have partial methods. Partial methods allow you to define a method signature in case someone wants to define it in another part of the partial class. This might seem pointless, but wait and see – it’s nice. Here’s how you declare a partial method:

// the code generated part public partial class MyPartialClass {
partial void DoIt(int x);
}

You can then implement it in another file like so:

// the hand-written part partial class MyPartialClass {
partial void DoIt(int x)
{
throw new NotImplementedException();
}
}

This is all a little abstract, right now, so let’s see how we can use this to implement a state machine framework. First we need a way to define a state machine. I’m going to use a simple XML file for this:

<?xml version="1.0" encoding="utf-8" ?> <StateModels> <StateModel ID="My" start="defcon1"> <States> <State ID="defcon1" name="defcon1"/> <State ID="defcon2" name="defcon2"/> <State ID="defcon3" name="defcon3"/> </States> <Inputs> <Input ID="diplomaticIncident" name="diplomaticIncident"/> <Input ID="assassination" name="assassination"/> <Input ID="coup" name="coup"/> </Inputs> <Transitions> <Transition from="defcon1" to="defcon2" on="diplomaticIncident"/> <Transition from="defcon2" to="defcon3" on="assassination"/> <Transition from="defcon3" to="defcon1" on="coup"/> </Transitions> </StateModel> </StateModels>

Here we have a really simple state machine with three states (defcon1, defcon2 and defcon3) as well as three kinds of input (diplomaticIncident, assassination and coup). Please excuse the militarism – I just finished watching a season of 24, so I’m all hyped up. This simple model also defines three transitions. it creates a model like this:

Microsoft released the Text Template Transformation Toolkit (T4) system with Visual Studio 2008. This toolkit has been part of GAT and DSL tools in the past, but this is the first time that it has been available by default in VS. It allows an ASP.NET syntax for defining templates. Here’s a snippet from the T4 template that generates the state machine:

<#@ template language="C#" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace="System.Xml" #>

<#
XmlDocument doc = new XmlDocument();
XmlElement xnModel = (XmlElement)doc.SelectSingleNode("/StateModels/StateModel");
string ns = xnModel.GetAttribute("ID");
XmlNodeList states = xnModel.SelectNodes("descendant::State");
XmlNodeList inputs = xnModel.SelectNodes("descendant::Input");
XmlNodeList trns = xnModel.SelectNodes("descendant::Transition");
#>
using System;
using System.Collections.Generic;

namespace <#=ns#> {
public enum <#=ns#>States : int{
<#
string sep = "";
foreach(XmlElement s in states)
{
Write(sep + s.GetAttribute("ID"));
WriteLine(@"// " + s.GetAttribute("name"));
sep = ",";
}

#>
} // end enum <#=ns#>States

public enum <#=ns#>Inputs : int{
<#
sep = "";
foreach(XmlElement s in inputs)
{
Write(sep + s.GetAttribute("ID"));
WriteLine(@"// " + s.GetAttribute("name"));
sep = ",";
}

#>
} // end enum <#=ns#>States

public partial class <#=ns#>StateModel{

public <#=ns#>StateModel()
{
SetupStates();
SetupTransitions();
SetStartState();
}
...

Naturally, there’s a lot in the template, but we’ll get to that later. First we need a representation of a state. You’ll see from the template that an enum get’s generated called <#=ns#>States. Here’s what it looks like for the defcon model.

public enum MyStates : int {
defcon1// defcon1 ,defcon2// defcon2 ,defcon3// defcon3 } // end enum MyStates 

This is still a bit too bare for my liking. I can’t attach an event model to these states, so here’s a class that can carry around one of these values:

public class State {
public int Identifier { get; set; }
public delegate void OnEntryEventHandler(object sender, OnEntryEventArgs e);
// ...public event OnEntryEventHandler OnEntryEvent;
// ...}

There’s a lot left out of this, but the point is that as well as storing an identifier for a state, it has events for both entry into and exit from the state. This can be used by the event framework of the state machine to provide hooks for your custom state transition and entry code. The same model is used for transitions:

public class StateTransition {
public State FromState { get; set; }
public State ToState { get; set; }
public event OnStateTransitioningEventHandler OnStateTransitioningEvent;
public event OnStateTransitionedEventHandler OnStateTransitionedEvent;
}

Here’s the list of inputs that can trigger a transition between states:

public enum MyInputs : int {
diplomaticIncident// diplomaticIncident ,assassination// assassination ,coup// coup } // end enum MyStates

The template helps to define storage for the states and transitions of the model:

public static Dictionary<<#= ns#>States, State> states                = new Dictionary<<#= ns#>States, State>();
public static Dictionary<string, StateTransition> arcs                = new Dictionary<string, StateTransition>();
public State CurrentState { get; set; }

which for the model earlier, will yield the following:

public static Dictionary<MyStates, State> states = new Dictionary<MyStates, State>();
public static Dictionary<string, StateTransition> arcs = new Dictionary<string, StateTransition>();
public State CurrentState { get; set; }

Now we can create entries in these tables for the transitions in the model:

private void SetStartState()
{
CurrentState = states[<#= ns#>States.<#=xnModel.GetAttribute("start")#>];
}

private void SetupStates()
{
<#
foreach(XmlElement s in states)
{
WriteLine("states[" + ns + "States."+s.GetAttribute("ID")+"] =               new State { Identifier = (int)"+ns+"States."+s.GetAttribute("ID")+" };");
WriteLine("states[" + ns + "States."+s.GetAttribute("ID")+"].OnEntryEvent               += (x, y) => OnEnter_"+s.GetAttribute("ID")+"();");
WriteLine("states[" + ns + "States."+s.GetAttribute("ID")+"].OnExitEvent               += (x, y) => OnLeave_"+s.GetAttribute("ID")+"(); ;");
}
#>
}
private void SetupTransitions()
{
<#
foreach(XmlElement s in trns)
{
#>
arcs["<#=s.GetAttribute("from")#>_<#=s.GetAttribute("on")#>"] = new StateTransition
{
FromState = states[<#= ns#>States.<#=s.GetAttribute("from")#>],
ToState = states[<#= ns#>States.<#=s.GetAttribute("to")#>]
};
arcs["<#=s.GetAttribute("from")#>_<#=s.GetAttribute("on")#>"].OnStateTransitioningEvent              += (x,y)=>MovingFrom_<#=s.GetAttribute("from")#>_To_<#=s.GetAttribute("to")#>;
arcs["<#=s.GetAttribute("from")#>_<#=s.GetAttribute("on")#>"].OnStateTransitionedEvent              += (x,y)=>MovedFrom_<#=s.GetAttribute("from")#>_To_<#=s.GetAttribute("to")#>;
<#
}
#>
}

which is where the fun starts. First notice that we create a new state for each state in the model and attach a lambda to the entry and exit events of each state. For our model that would look like this:

private void SetupStates()
{
states[MyStates.defcon1] = new State {Identifier = (int) MyStates.defcon1};
states[MyStates.defcon1].OnEntryEvent += (x, y) => OnEnter_defcon1();
states[MyStates.defcon1].OnExitEvent += (x, y) => OnLeave_defcon1();

states[MyStates.defcon2] = new State {Identifier = (int) MyStates.defcon2};
states[MyStates.defcon2].OnEntryEvent += (x, y) => OnEnter_defcon2();
states[MyStates.defcon2].OnExitEvent += (x, y) => OnLeave_defcon2();

states[MyStates.defcon3] = new State {Identifier = (int) MyStates.defcon3};
states[MyStates.defcon3].OnEntryEvent += (x, y) => OnEnter_defcon3();
states[MyStates.defcon3].OnExitEvent += (x, y) => OnLeave_defcon3();
}

For the Transitions the same sort of code gets generated, except that we have some simple work to generate a string key for a specific <state, input> pair. Here’s what comes out:

private void SetupTransitions()
{
arcs["defcon1_diplomaticIncident"] = new StateTransition {
FromState = states[MyStates.defcon1],
ToState = states[MyStates.defcon2]
};
arcs["defcon1_diplomaticIncident"].OnStateTransitioningEvent                  += (x, y) => MovingFrom_defcon1_To_defcon2;
arcs["defcon1_diplomaticIncident"].OnStateTransitionedEvent                 += (x, y) => MovedFrom_defcon1_To_defcon2;
arcs["defcon2_assassination"] = new StateTransition {
FromState = states[MyStates.defcon2],
ToState = states[MyStates.defcon3]
};
arcs["defcon2_assassination"].OnStateTransitioningEvent                += (x, y) => MovingFrom_defcon2_To_defcon3;
arcs["defcon2_assassination"].OnStateTransitionedEvent                += (x, y) => MovedFrom_defcon2_To_defcon3;
arcs["defcon3_coup"] = new StateTransition {
FromState = states[MyStates.defcon3],
ToState = states[MyStates.defcon1]
};
arcs["defcon3_coup"].OnStateTransitioningEvent                += (x, y) => MovingFrom_defcon3_To_defcon1;
arcs["defcon3_coup"].OnStateTransitionedEvent                += (x, y) => MovedFrom_defcon3_To_defcon1;
}

You can see that for each state and transition event I’m adding lambdas that invoke methods that are also being code generated. these are the partial methods described earlier. Here’s the generator:

foreach(XmlElement s in states)
{
WriteLine("partial void OnLeave_"+s.GetAttribute("ID")+"();");
WriteLine("partial void OnEnter_"+s.GetAttribute("ID")+"();");
}
foreach(XmlElement s in trns)
{
WriteLine("partial void MovingFrom_"+s.GetAttribute("from")+"_To_"+s.GetAttribute("to")+"();");
WriteLine("partial void MovedFrom_"+s.GetAttribute("from")+"_To_"+s.GetAttribute("to")+"();");
}

Which gives us:

partial void OnLeave_defcon1();
partial void OnEnter_defcon1();
partial void OnLeave_defcon2();
partial void OnEnter_defcon2();
partial void OnLeave_defcon3();
partial void OnEnter_defcon3();
partial void MovingFrom_defcon1_To_defcon2();
partial void MovedFrom_defcon1_To_defcon2();
partial void MovingFrom_defcon2_To_defcon3();
partial void MovedFrom_defcon2_To_defcon3();
partial void MovingFrom_defcon3_To_defcon1();
partial void MovedFrom_defcon3_To_defcon1();

The C# 3.0 spec states that if you don’t choose to implement one of these partial methods then the effect is similar to attaching a ConditionalAttribute to it – it gets taken out and no trace is left of it ever having been declared. That’s nice, because for some state models you may not want to do anything other than make the transition.

We now have a working state machine with masses of extensibility points that we can use as we see fit. Say we decided to implement a few of these methods like so:

public partial class MyStateModel {
partial void OnEnter_defcon1()
{
Debug.WriteLine("Going Into defcon1.");
}
partial void OnEnter_defcon2()
{
Debug.WriteLine("Going Into defcon2.");
}
partial void OnEnter_defcon3()
{
Debug.WriteLine("Going Into defcon3.");
}
}

Here’s how you’d invoke it:

MyStateModel dfa = new MyStateModel();
dfa.ProcessInput((int) MyInputs.diplomaticIncident);
dfa.ProcessInput((int) MyInputs.assassination);
dfa.ProcessInput((int) MyInputs.coup);

And here’s what you’d get:

Going Into defcon2.
Going Into defcon3.
Going Into defcon1.

There’s a lot you can do to improve the model I’ve presented (like passing context info into the event handlers, and allowing some of the event handlers to veto state transitions). But I hope that it shows how the partials support in conjunction with T4 templates makes light work of this perennial problem. This could easily save you from writing thousands of lines of tedious and error prone boiler plate code. That for me is a complete no-brainer.

What I like about this model is the ease with which I was able to get code generation. I just added a file with extension ‘.tt’ to VS 2008 and it immediately started generating C# from it. All I needed to do at that point was load up my XML file and feed it into the template. I like the fact that the system is lightweight. There is not a mass of framework that takes over the state management, it’s infinitely extensible, and it allows a very quick turnaround time on state model changes.

What do you think? How would you tackle this problem?

# Functional Programming – lessons from high-school arithmetic

I’ll start out with an apology – it was only by writing this post, that I worked out how to write a shorter post on the same topic. Sometime I’ll follow this up with something less full of digressions, explorations or justifications. The topic of the post started out as ‘Closure‘. It then became ‘Closure plus Rules of Composition‘ and finally ended up as ‘functional programming – lessons from high school arithmetic‘. The point of this post is to explore the API design principles we can learn from rudimentary high school arithmetic.  You already know all the mathematics I’m going to talk about, so don’t be put off by any terminology I introduce – it’s only in there to satisfy any passing mathematicians. ;^]

The topic of this post is much more wide-ranging than the previous ones. The post will eventually get around to talking about API design, but I really started out just wanting to dwell on some neat ideas from philosophy or mathematics that just appealed to me. The first idea is ‘Closure‘.

Closure has many meanings, but the two most relevant to this blog are:

• A function that gets evaluated with a bound variable
• A set that is closed under some operation.

It’s this second meaning that I want to explore today – it’s one of those wonderful philosophical rabbit holes that lead from the world of the mundane into a wonderland of deeply related concepts. As you’ll already know if you’ve read any of my earlier posts on functional programming, I am not a mathematician. This won’t be a deep exposition on category theory, but I do want to give you a flavour so that hopefully you get a sense of the depth of the concepts I’m talking about.

First let’s start with two little equations that seem to bear almost no information of interest:

(1)     1 + 1 = 2

and

(2)     2 – 1 = 1

(1) involves adding two natural numbers to get another natural number. (2) involves subtracting one natural number from another to get a third natural number. They seem to be very similar, except for the fact that if you keep repeating (2) you eventually get a negative number which is not a natural number. If you repeatedly perform addition, you can go on forever. That property is called ‘closure‘. It means that if you perform addition on any natural number you are guaranteed to get a valid result. That closure guarantee for some operations is one of the first things I want you to ponder – some operations give you guarantees of object validity, while others don’t. We need to learn how to spot those ideas.

Another interesting thing that some introspection reveals about equation (2) is that the set from which it takes it’s values is bounded in one direction, and that at the lower bound is a value that is idempotent for the operation. That term idempotent is daunting to us non-mathematicians but what it means is simply that when the operation is performed the result remains unchanged, no matter how many times it gets performed. Here’s another thing that is worth pondering – some operations are stable because they guarantee not to change your state.

Digression. Why on earth would anyone ever waste their time in writing code that was designed at the outset to do nothing? It seems like the ultimate exercise in futility. The answer is that idempotent operations are not doing nothing when in the presence of ‘rules of combination’. With rules of combination (of which more later), idempotent operations become a useful tool in composing functions.

SubDigression: A rule of combination is a feature of a system allowing you to combine distinct entities of a domain together to form a new entity. You can see how this relates to closure. It relates to closure on two levels. For example, when adding two integers:

• The result of adding two integers is an integer. That’s closure on the set of integers.
• The composition of two closed functions is itself closed. That’s closure at the level of functions on integers.

In other words, you can choose to provide closure at the level of domain object, or on the functions that manipulate them. LINQ queries of type IQueryable<T> are a good example. You can combine together two queries to get a sequence of T, thus providing domain-level closure. You can also combine together IQueryables to create new IQueryables that also yield sequences of T. That’s functional closure. LINQ is closed on both levels. It’s closed at the level of the entities that it is retrieving, but it’s also closed at the level of the functions it uses to represent queries.

It’s that level of composability that gives LINQ its power. And finding those design principles that we can apply to our own APIs is the purpose of this post. Ponder this: we don’t often provide rules of combination in our object models. If we did, our systems would probably be more flexible. End of SubDigression

Several years ago I produced a graphics library for producing montages in a telepathology app. The system used a scripted generator to produce a tree of graphics operations. Each node on the tree manipulated an image then passed it on to its children. Without an idempotent operation it would have been extremely difficult to add orthogonal operations  (like comms, or microscope operations) or to bind together trees, or to create a default root of an operation graph.

The point of this outer-digression is that there are plenty of cases where at first sight Idempotence seems like architectural overkill. When you have rules of combination you find idempotent operations complete the puzzle making everything just click together. While the idempotent operation does nothing, it creates a framework on which other operations can be composed. Ponder this: Sometimes targeting an architectural abstraction might seem overkill, but if done wisely it can yield great simplicity and flexibility. If you don’t believe this – play with LINQ a little. End of Digression.

If these were properties that only applied to natural numbers under addition or subtraction then they wouldn’t be worth a blog post. It’s the fact that this is a pattern that can be observed in other places that makes them worth my time writing about, and your time reading. Lets stay with integers a bit longer, though:

(3)     2 * 2 = 4

(4)     1 * 2 = 2

You probably noticed right away that the number 1 is idempotent in (4). We could keep multiplying by 1 till the cows come home and we’d always get 2. Now, I’m not setting out to explore the idea of idempotence. The reason I’m mentioning it is that it is an important property of an algebraic system. Closure is another. When you multiply two integers together you get another integer – that’s closure.

Just as addition has it’s inverse in the form of subtraction, so too does multiplication have an inverse in the form of division. Take a look at this:

(5)     4 / 2 = 2

(6)     1 / 2 = 0.5

In (6), the result is not an integer. As an interesting byline – the history of mathematics is littered with examples where new branches of mathematics were formed when non-closed operations were performed that led to awkward results. The process of creating a closed version of an operation’s inverse led mathematicians to create new mathematical structures with new capabilities, thus extending mathematics’ reach. The non-closure of subtraction (the inverse of addition) led to the introduction of the integers over the natural numbers. The non-closure of the division operation (the inverse of multiplication) led to the introduction of the rational numbers over the integers. And the non-closure of the square root operation (the inverse of the power operation) led to the introduction of the irrational numbers. On many occasions through history the inverse of an everyday closed operation has led to the expansion of the space of possible data types. Ponder that – attempting to produce data structures on which the inverses of closed operations are also closed can lead to greater expressivity and power. A bit of a mouthful, that, and probably not universally true, but its something to ponder.

Again, if that were all there were to the idea, I (as a programmer) probably wouldn’t bother to post about it – I’d leave it to a mathematician. But that is not the limit to closure. Closure has been recognized in many places other than mathematics – from physics to philosophy and from API to language design. Lets describe an algebraic system in the abstract to isolate what it means to be closed. The simplest mathematical structure that fits my description is called a Magma:

(7)     A Magma is any set $M$ equipped with a binary function $M \times M \rightarrow M$

This kind of thing is known to mathematicians as an Algebraic Structure. There are LOTS of different kinds, but that’s one digression I’m not going to make. One thing to notice is that closure is built into this most basic of algebraic structures. What $M \times M \rightarrow M$ means is that if you apply the operation ‘$\times$ ‘ to the two values from $M$ you get another value from $M$. By that definition, division doesn’t qualify as a Magma if the set $M$ is integers, but it does if the set is the rational numbers.

(8)     2 + 3 + 5 = 10

(9)     (2 + 3) + 5 = 10

(10)     2 + (3 + 5) = 10

Each of these equations demonstrates what is known as associativity. If you add that to the definition of a Magma, you get what is called a semigroup. Integers with addition have that property of associativity, so it counts as a semigroup.

(11)     2 – 3 -5 = -6

(12)     (2 – 3) – 5 = -6

(13)     2 – (3 – 5) = 4

Clearly the subtraction operation on the integers is not associative, so it doesn’t qualify to be called a semigroup.  Try this on for size – associative operations are inherently flexible and composable. Abelson and Sussman even went so far as to say that designing systems with such properties was a better alternative to the traditional top-down techniques of software engineering.

We saw earlier that the property of idempotence means that there may be an element that yields the same value for that operation. If the Magma has an identity property, then it is called a ‘loop’. The point of this is to point out the other properties that operations can have (and how they contribute to membership of an algebraic structure). The key properties are:

• Closure
• Associativity
• Identity
• Inversibility

I’m going to throw a code snippet in at this point. If you’re a programmer with no particular interest in algebra, you might be wondering what on earth this has to do with programming

var q = from u in MyDataContext.Users
where u.Name.StartsWith("And")
select u;

var q2 = from v in q
where v.Name.EndsWith("rew")
select v;

Here’s an example taken from something like LINQ To SQL. Take a look at the ‘where’ keyword. It is clearly closed, since the application of where to a query yields another query (regardless of whether it gives you any useful results). The example is also associative, since you can reverse the order of the clauses and the resulting set will be the same. LINQ has an identity as well – “.Where(t => t)” which does nothing. LINQ lacks and inversion operation, so you can’t add a clause, then cancel it out with another – instead, if you tried to do that, you’d get no results or everything. Here’s something to ponder – would link be more or less powerful if it had the property of inversibility? It’s clearly possible (though probably extremely difficult to implement).

I started thinking about these ideas because I wanted to understand why LINQ is powerful. It’s flexible and easy to understand because of the  mathematical ‘structure’ of the standard query operations. Ponderable: is any API going to be more powerful and flexible (and less brittle) if it displays some of the properties of an algebraic structure?

What are the advantages of creating APIs that have group structure? Just because we could design an API that has a group structure does not mean that we must. There must be an advantage to doing so. So far I have only hinted at those advantages. I now want to state them directly. If “we can regard almost any program as the evaluator for some language“[r], then we can also regard some languages as a more effective representation of a domain than others.  For many years, I’ve felt that the object oriented paradigm was the most direct and transparent representation of a domain. At the same time, I also felt there was something lacking in the way operations on an OO class work (in a purely procedural approach).

To cleanly transition the state of a class instance to another state, you (should) frequently go to extreme lengths[r] to keep the object in a consistent state. This kind of practice is avoided in those cases where it is feasible to use immutable objects, or more importantly to design your API so that the objects passed around might as well be immutable. Consider a class in C++ that implements the + operator. You could implement the operator in two ways:

1. add the value to the right to this, and then return this.
2. create a temporary object, add the value on the right to it and return the temporary object.

The following pseudo-code illustrates the point by imaging a class that supports “operator +”:

MyClass a = new MyClass();
MyClass b = new MyClass();
MyClass c = new MyClass();
MyClass d = a + b + a + c;

If you implement ‘+’ using technique 1 the result in d is $(3a + b + 3c)$ whereas if you implement it using technique 2, the result in d is correctly $(2a + b + c)$. Can you work out where the 3c comes from? The state, being mutable, is modified in a way that is incorrect during the addition operator. The operands of an operation like ‘+’ should be unaffected by the fact that they took part in the assignment of a value to d. Something else to ponder: immutable objects or operations can make it easier to produce clean APIs that work with the language to create a correct answer.

You might complain that what I’m aiming for here is a programming style that uses mathematical operators to implement what would be otherwise done using normal methods. But you’d be missing the point. Whether your method is called ‘+’ or if it’s called ‘AddPreTaxBenefits’ is irrelevant. The structure of the operation, at the mathematical level, is the same. And the same principles can apply.

The method signature of a closed method is $T 'times T \rightarrow T$. There are plenty of methods that don’t fit this model. Lets pick one that pops into my mind quite readily – bank account transactions:

void Transfer(Account debit, Account credit, decimal sumToTransfer);

There is an entity in here that does fit the bill for such group like transactions – Money. There are endless complexities in financial transactions between currencies, like currency conversion, exchange rates and catching rounding errors. But the point is that it makes sense to be able to implement group operators on currency values. That ability allows you to define a language of currencies that can be exploited on a higher level item of functionality – the Account. BTW: I’m not talking about the algebraic structure of addition on decimals. I’m talking about adding values of locale specific money values – a different thing.

void Transfer(Account debit, Account credit, Currency sumToTransfer)
{
debit.Balance = debit.Balance - sumToTransfer;
credit.Balance = credit.Balance + sumToTransfer;
}

Would it be better to define the operation on the Account class itself? The operator might actually be updating the internal balance property, but we don’t care about that.

void Transfer(Account debit, Account credit, Currency sumToTransfer)
{
debit = debit - sumToTransfer;
credit = credit + sumToTransfer;
}

Lets take a look and see whether operator ‘+’ fits the criteria we defined earlier for group-like structures:

Closed If you take an account and you add a value to it, you get another valid account, so yes, this is closed.

Associative Yes – though I’m not sure what that would mean in terms of bank accounts. Double entry bookkeeping is kinda binary…

Identity OK – The identity element of the ‘+’ operation on accounts is the zero currency value.

Inverse operation Easy – subtraction. Or the negative currency value. Do you allow negative currency values? that’s incompatible with double entry bookkeeping, so it might not be possible to provide an inverse operator for some systems. There’s an example where trying to get an inverse could lead you to change the design of your system.

This approach passes the criteria, but it also highlights a conceptual layer difference between money types and bank account types that makes for an awkward API if you try to treat them as equivalent. From a design perspective you can see that if there are non-obvious rules about how you can combine the elements of your class, you’re no better off than with a conventional API design. One thing that does occur to me, though, is that the inconclusive group structure here pointed to a mismatch of levels. The addition operator applies at the level of quantities of cash – account balances. Accounts are more than just balances, and attempting to make them behave like they were nothing more than a number highlights the pointlessness of doing so. Ponder this: the concept of ‘levels’ may be something that arises naturally out of the algebraic structure of the entities in a system? I’m not sure about this yet, but it’s an intriguing idea, don’t you think?

Obviously, we could have expected group structure at the level of balances, since we’re dealing with real numbers that are a known group under addition and subtraction. But what about higher level classes, like bank accounts? What are the operations we can perform on them that fits this structure?

I wasn’t sure whether I’d come away with any conclusions from this post, but I did come away with some very suggestive ideas to ponder:

• Some operations give you guarantees of object validity. As a programmer, you need to learn how to spot them.
• Some operations are preferable because they guarantee not to change your state.
• Provide rules of combination in our object models would probably make them more flexible.
• Sometimes abstraction might seem overkill, but if used wisely it can yield great simplicity and flexibility. If you don’t believe this – play with LINQ a little.
• Produce data structures on which the inverses of closed operations are also closed can lead to greater expressivity and power.
• Associative operations are inherently flexible and composable.
• Maybe all APIs will be more expressive and flexible (and less brittle) if they displays some of the properties of an algebraic structure?
• Immutable objects or operations can make it easier to produce clean APIs that work with the language to create a correct answer.
• Trying to get an inverse for an operation could lead you to change the design of your system.
• The concept of ‘levels’ may be something that arises naturally out of the algebraic structure of the entities in a system.

It’s funny that these ideas flow simply from looking at high-school algebra, especially since some of them read like a functional-programming manifesto. But, hopefully, you’ll agree that some of them have merit. They’re just thoughts that have occurred to me from trying to understand an offhand comment by Eric Mejer about the relationship between LINQ and Monads. Perhaps I’ll pursue that idea some more in future posts, but for now I’ll try to keep the posts coming more frequently.

# Søren on DBC

Recently, Søren Skovsbøll wrote a excellent follow up to a little post I did a while back on using C# 3.0 expression trees for representing predicates in design by contract. The conclusion of that series was that C# was inadequate in lots of ways to the task of doing design by contract. Having said that, you can still achieve a lot using serialisation of object states and storage of predicates for running before and after a scope.

Søren was not happy with the format of errors being reported, nor the potential for massive serialisation blowout. Rather than comment on the blog, he went away and did something about it. And it’s pretty good! Go take a look, and then pick up the baton from him. Your challenge is to extract the parmeter objects from the expression trees of the predicates and take lightweight snapshots of the objects refered to. You also need a “platform independent” way to serialize objects for this scheme (i.e. one that doesn’t depend on XmlSerialisation or WCF data contracts.

Think you can do it? Apply here!😛

# Functional Programming in C# – Higher-Order Functions

This is the second in a series on the basics of functional programming using C#. My topic today is one I touched on last time, when I described the rights and privileges of a function as a first class citizen. I’m going to explore Higher-Order Functions this time. Higher-Order Functions are functions that themselves take or return functions. Meta-functions, if you like.

As I explained last time, my programming heritage is firmly in the object-oriented camp. For me, the construction, composition and manipulation of composite data structures is second nature. A higher-order function is the equivalent from the functional paradigm. You can compose, order and recurse a tree of functions in just the same way as you manipulate your data. I’m going to describe a few of the techniques for doing that using an example of pretty printing some source code for display on a web site.

I’ve just finished a little project at Readify allowing us to conduct code reviews whenever an interesting code change gets checked into our TFS servers. A key feature of that is pretty-printing the source before rendering it. Obviously, if you’re displaying XHTML on an XHTML page, your browser will get confused pretty quickly unless you take steps to HTML-escape all the XHTML entities that might corrupt the display. The examples I’ll show will highlight the difference between the procedural and functional approaches.

This example shows a fairly typical implementation that takes a file that’s been split into lines:

public static string[] RenderLinesProcedural(string[] lines)
{
for (int i = 0; i < lines.Count(); i++)
{
lines[i] = EscapeLine(lines[i]);
}
return lines;
}

public static string EscapeLine(string line)
{
Debug.WriteLine(“converting ” + line);
return line.Replace(” “, ”  “)
.Replace(“\t”, ”  “)
.Replace(“<“, “<“)
.Replace(“>”, “>”);
}

There’s a few things worth noticing here. In C#, strings are immutable. That means that whenever you think that you are changing a string, you’re not. In the background, the CLR is constructing a modified copy of the string for you. The Array of strings on the other hand is not immutable, therefore a legitimate procedural approach is to make an in-place modification of the original collection and pass that back.  The EscapeLine method repeatedly makes modified copies of the line string passing back the last copy.

Despite C# not being a pure functional programming language[1], it’s still doing a lot of copying in this little example. My early impression was that pure functional programming (where all values are immutable) would be inefficient because of all the copying goign on. Yet here is a common-or-garden object oriented language that uses exactly the same approach to managing data, and we all use it without a qualm. In case you didn’t know, StringBuilder is what you should be using if you need to make in-place modifications to strings.

Let’s run the procedural code and record what happens:

private static void TestProcedural()
{
Debug.WriteLine(“Converting the lines”);
IEnumerable<string> convertedStrings = RenderLinesProcedural(originalLines);
Debug.WriteLine(“Converted the lines?”);

foreach (string s in convertedStrings)
{
Debug.WriteLine(s);
}
}

Here’s the output:

As you can see, the lines all got converted before we even got to the “converted the lines?” statement. That’s called ‘Eager Evaluation’, and it certainly has its place in some applications. Now lets use Higher-Order Functions:

public static IEnumerable<string> RenderLinesFunctional(IEnumerable<string> lines)
{
return lines.Map(s => EscapeString(s));
}

static IEnumerable<R> Map<T, R>(this IEnumerable<T> seq, Func<T, R> f)
{
foreach (var t in seq)
yield return f(t);
}

static string EscapeString(string s)
{
Debug.WriteLine(“converting ” + s);
return s.Replace(”  “, “&nbsp;&nbsp;”)
.Replace(“\t”, “&nbsp;&nbsp;”)
.Replace(“<“, “&lt;”)
.Replace(“>”, “&gt;”);
}

private static void TestFunctional()
{
Debug.WriteLine(“Converting the lines”);
IEnumerable<string> convertedStrings = RenderLinesFunctional(originalLines);
Debug.WriteLine(“Converted the lines?”);

foreach (string s in convertedStrings)
{
Debug.WriteLine(s);
}
}

This time the output looks different:

At the time that the “Converted the Lines?” statement gets run, the lines have not yet been converted. This is called ‘Lazy Evaluation[2]’, and it’s a powerful weapon in the functional armamentarium. For the simple array that I’m showing here, the technique looks like overkill but imagine that you were using a paged control on a big TFS installation like Readify’s TFSNow. You might have countless code reviews going on. If you rendered every line of code in all the files being viewed, you would waste both processor and bandwidth resources needlessly.

So what did I do to change the way this program worked so fundamentally? Well the main thing was to opt to use the IEnumerable interface, which then gave me the scope to provide an alternative implementation to representing the collection. in the procedural example, the return type was a string array, so I was bound to create and populate the array before returning from the function. That’s a point worth highlighting: Use iterators as return types where possible – they allow you to mix paradigms. Converting to IEnumerables is not enough. I could change the signature of TestProcedural to use iterators, but it would still have used Eager Evaluation.

The next thing I did was use the Map function to return a functional iterator rather than a concrete object graph as was done in the procedural example. I created Map here to demonstrate that there was no funny LINQ business going on in the background. In most cases I would use the Enumerable.Select() extension method from LINQ to do the same thing. Map is a function that is common in functional programming, it allows the lazy transformation of a stream or collection into something more useful. Map is the crux of the transformation – it allows you to insert a function into the simple process of iterating a collection.

Map is a Higher-Order Function, it accepts a function as a parameter and applies it to a collection on demand. Eventually you will need to deal with raw data – such as when you bind it to a GridView. Till that point you can hold off on committing resources that may not get used. Map is not the only HOF that we can use in this scenario. We’re repeatedly calling String.Replace in our functions. Perhaps we can generalise the idea of repeatedly calling a function with different parameters.

Func<T, T> On<T>(this Func<T, T> f, Func<T, T> g)
{
return t => g(f(t));
}

This method encapsulates the idea of composing functions. I’m creating a function that returns the result of applying the inner function to an input value of type T, and then applying the outer function to the result. In normal mathematical notation this would be represented by the notation “g o f”, meaning g applied to f. Composition is a key way of building up more complex functions. It’s the linked list of the functional world – well it would be if the functional world were denied normal data structures, which it isn’t.😛

Notice that I’m using an extension method here, to make it nicer to deal with functions in your code. The next example is just a test method to introduce the new technique.

private static void TestComposition()
{
var seq1 = new int[] { 1, 3, 5, 7, 11, 13, 19 };
var g = ((Func<int, int>)(a => a + 2)).On(b => b * b).On(c => c + 1);
foreach (var i in seq1.Map(g))
{
Debug.WriteLine(i);
}
}

TestComposition uses the ‘On’ extension to compose functions into more complex functions. The actual function is not really that important, the point is that I packaged up a group of functions to be applied in order to an input value and then stored that function for later use. You might think that that’s no big deal, since the function could be achieved by even the most trivial procedure. But this is dynamically composing functions – think about what you could do with dynamically composable functions that don’t require complex control logic to make them work properly. Our next example shows how this can be applied to escaping strings for display on a web page.

void TestComposition2()
{
var strTest = @”<html><body>hello world</body></html>”;
string[][] replacements = new[]
{
new[]{“&”, “&amp;”},
new[]{”  “, “&nbsp;&nbsp;”},
new[]{“\t”, “&nbsp;&nbsp;”},
new[]{“<“, “&lt;”},
new[]{“>”, “&gt;”}
};

Func<string, string> f = x => x;
foreach (string[] strings in replacements)
{
var s0 = strings[0];
var s1 = strings[1];
f = f.On(s => s.Replace(s0, s1));
}

Debug.WriteLine(f(strTest));
}

This procedure is again doing something quite significant – it’s taking a data structure and using that to guide the construction of a function that performs some data-driven processing on other data. Imagine that you took this from config data or a database somewhere. The function that gets composed is a fast, directly executable, encapsulated, interface free, type safe, dynamically generated unit of functionality. It has many of the benefits of the Gang Of Four Strategy Pattern[3].

The techniques I’ve shown in this post demonstrate some of the power of the functional paradigm. I described how you can combine higher order functions with iterators to give a form of lazy evaluation. I also showed how you can compose functions to build up fast customised functions that can be data-driven. I’ve also shown a simple implementation of the common Map method that allows a function to be applied to each of the elements of a collection. Lastly I provided a generic implementation of a function composition mechanism that allows you to build up complex functions within a domain.

Next time I’ll introduce the concept of closure, which we’ve seen here at work in the ‘On’ composition function.

Some references:

1. Wikipedia: Pure Functions

2. Wikipedia: Lazy Evaluation

3. Wikipedia: Strategy Pattern