Tag Archives: functional programming

Functional Spreadsheet in F#

For anyone interested in how to solve a real problem using F#, I suggest reading this post on Developer Fusion. It is an implementation of the core functionality of a spreadsheet. It includes a full parsing and expression evaluation engine, plus databinding and display (silverlight… eww, but it’s mainly so you can try it in your browser). Reading it and looking at the use of Active Patters, Pattern Matching and Discriminated Unions really drives home how language features can lead to clear and concise implementations of algorithms that are often awkward to implement in true OO fashion.

The full code snippet is available here, and can be run inside your browser here.

Recommended.

Tagged , ,

10 One Liners to Impress Your Friends

As a bit of a programming language geek I find that comparing programming languages is a worthwhile exercise mainly because of the different techniques and styles that you are exposed to.
Learning multiple programming languages is one of the best things you can do to gain intuition about the most expressive way to write your code in any language.
No matter how much of an expert you are in a given language, learning a new one is often a humbling and educational experience and one that we should all try to do every so often to keep ourselves sharp.

I’ve seen several articles going around showcasing ‘one-liners’ (single lines of code) in different languages to perform a set of 10 simple tasks.
The first one I saw was done in Scala, and quickly spawned a number of imitations in other languages:

They are worth a look if only for a nice take on FizzBuzz – the Jeff Atwood smoke-test of programmer competency:

Enumerable.Range(1, 15).Select((i)=>i + (i%3==0?"fizz":"") + (i%5==0?"buzz":""));

C# is getting much more expressive with LINQ extension methods and lambda expressions but I think F# still has the edge with some of the inbuilt list processing functions.
Take partitioning a list into two lists based on a predicate in C#:

var passed = new List<int>();
var failed = new List<int>();
(from bucket in new[] { passed, failed } from i in new[] { 49, 58, 76, 82, 88, 90 } select new { bucket, i }).ToList().ForEach((tuple) => tuple.bucket.AddRange(Enumerable.Repeat(tuple, 1).Where((tup) => (tup.bucket == passed && tup.i > 60) || (tup.bucket == failed && tup.i <= 60)).Select((tup) => tup.i)));

Now in F#:

[49; 58; 76; 82; 88; 90] |> List.partition (fun i -> i > 60);;

If you look at the links above and see which language is most expressive for solving each problem you can really start to understand how languages can affect productivity.
Just being Turing Complete isn’t enough these days, and thank god for that

Tagged , , , ,

Y-Combinator in Objective-C

A GitHub user named Joshua Ballenco recently posted a project called y.h.
It’s an implementation of the Y-Combinator which is used in functional programming to achieve recursion using anonymous functions.
Apple is lucky to have talented people trying to make their language nicer to use.
Apple did well adding Blocks(closures) to Objective-C which slightly modernises the language. Unfortunately even with (because of?) Cocoa it’s not very expressive…

I mean look at this:

RecurBlock factorial = YComb((NSNumber *) ^(NSNumber *val) {
if([val compare: [NSNumber numberWithInt: 0]] == NSOrderedSame) {
return [NSNumber numberWithInt:1];
} else {
NSNumber *next_val = this_block([NSNumber numberWithInt:([val intValue] - 1)]);
return [NSNumber numberWithInt:([val intValue] * [next_val intValue])];
}
});

Could well be the least expressive implementation of a recursive factorial ever.
I’m not sure I know what to say…

Maybe MacRuby will save us all!

Tagged , , ,

Method Chaining in C# or “This is not a post about Monads (yet!)”

Looking at the previous post people unfamiliar with F# might have noticed the copious use of

|>

the ‘pipe’ operator.

Essentially, it allows you to chain methods in a more readable way by giving you a binary operator where the left side is a value v and the right side is a function f, the result of the operator is simply f(v);

This can be nice for expressing operations involving lists and the like, but its usefulness extends to pretty much anytime you have to do Something(ToThis(BecauseOfThis(x)));

I thought about how useful it would be to implement the pipeline operator in C# to give the ability to express those operations cleanly.

A simple implementation could be an extension method like this:

public static U AndThen<T,U>(this T val, Func<T, U> f) { return f(val); }

Which would let you write things like this:

var dateInt = "2009/11/03"
. AndThen(x => x.Replace("/","")
. AndThen(x => Convert.ToInt32(x));

Not bad – but what if the Convert.ToInt32 throws an exception?

In normal C# you would have to write a bunch of nested if statements, each time checking for nulls or exceptions, and handle them with several else blocks.
This problem (and how to handle it) is well-understood in functional programming and people have developed a very elegant solution.
I won’t go into what a Monad is in this post (another time!), but what if we had a wrapper class that could turn any class into one that optionally had a value. Kind of like nullable types in .NET (except they can only be used with structs and value types, which motivates this post).

What if you could have something like List? to represent a value that may or may not contain a list of ints?
Let’s call this class Maybe (this implementation is courtesy of this blogger who did a great post on Monads in C# here)

	public class Maybe<T>
	{
	    public readonly static Maybe<T> Nothing = new Maybe<T>();
		
	    public T Value { get; private set; }
		
	    public bool HasValue { get; private set; }
		
	    Maybe()
	    {
	        HasValue = false;
	    }
		
	    public Maybe(T value)
	    {
	        Value = value;
	        HasValue = true;
	    }
	}	

If we add some methods to Maybe , maybe becomes a Monad, but we will talk about what that means in a later post.

With this Maybe class in hand, we can start to define an interface for method chaining that can handle problems that occur during invoking one method in the chain. If one of them has an issue, the result of the entire expression will be Maybe.Nothing.

We can set it up so that if a method lower down the chain gets passed a Nothing, it knows not to do anything but simply pass along the nothing.

We have now encapsulated the control flow of continuously testing for nulls.
I have a quick implementation up here on GitHub that I will likely develop further because there is lots more to explore in this space.

So we can handle exceptions and nulls silently:

			var val = "1234a ".If()
			.And(x => x.Trim())
			.And(x => Convert.ToInt32(x)); //throws exception
			Assert.IsFalse(val.HasValue); //true

			var val = "1234 ".If()
			.And(x => (string)null) //returns null
			.And(x => Convert.ToInt32(x));
			Assert.IsFalse(blah.HasValue); //true

Haskell being a pure functional language represents Exceptions this way, but we live in the .NET world and even in F# we might want side effects or be interacting with libraries that do.
So we can provide functions that are invoked when the value changes from Something to Nothing:

			string errorLog = String.Empty;
			var val = "1234a ".If()
			.And(x => x.Trim())
			.And(x => Convert.ToInt32(x), (x,e)=> errorLog = "couldn't convert integer" + e.ToString());
			Assert.IsFalse(String.IsNullOrEmpty(errorLog));

We also might want to provide a general failure side effect (for logging, say):

			string errorLog = String.Empty;
			var val = "1234a ".If()
			.And(x => x.Trim())
			.And(x => Convert.ToInt32(x))
			.FailWith(()=> errorLog = "operation failed");
			Assert.IsFalse(String.IsNullOrEmpty(errorLog));

This library is useful for method chaining and handling exceptions and other cases, but if you wanted to put in transparent logging or something similar you would still be forced to put it explicitly in the error continuation functions.
This is something that could be handled monadically but I haven’t thought enough about how to integrate that yet with a fluent interface in C#.

In F# you could use computation expressions (Monads!) and so encase all your statements in, say, log {}, as long as you implemented the monadic axioms for log, but syntactically that would end up pretty ugly in C#.

The source for this library is available on GitHub in a collection of functional utility classes I’ve been playing with here.

Check out the unit test project for more examples if you’re interested.

Tagged , , , , , , ,

Pattern Matching in C#

Many functional languages have the construct of ‘pattern matching’ baked in to the language.
OCaml, F#, and Haskell all use it as a concise, expressive, and safe (we’ll get to that later) way to handle flow control or even to define entire functions.
In F# it looks like this:

let login user =	
match user with	
 | "hypermush" -> printfn "Hello, Martin"	
 | "admin" -> printfn "Hello, Sir"	
 |  x -> printfn "Hello, %s" x;;

This may look simple, but there is a lot going on here.
Using the match syntax we take the value (in this case ‘name’) and test if it matches any of the patterns (the expressions on the left hand side of the ‘->’).
The first pattern to match executes the statement on the right hand side of the arrow. We then leave the statement.
The first thing to notice is that the first two patterns match string literals while the last actually binds the value name to x and uses that value in the continuation function.
The second thing to notice is that these continuation functions may have side effects and call other functions (or recurse), which allows us to write nontrivial functions that consist entirely of a pattern match. It’s not hard to see how pattern matching is concise and expressive compared to a bunch of if/else blocks, but how is it ‘safe’?
Well, in a strongly typed language like F# with fancy type-inference the compiler can give you warnings that let you reason about the correctness of a program. When you use pattern matching you are being explicit with your intent to dispatch and this can be powerful.

For example, if your patterns are incomplete (ie. there is a case for which you have not specified a continuation), the F# compiler will warn you:

let who l =	match l with	
 | 'Me' -> 1 	
 | 'You' -> 2;;


FS0025: Incomplete pattern matches on this expression. For example, the value '' '' may indicate a case not covered by the pattern(s).

Let’s say you ignore the warning and continue on. At runtime, failure to match a pattern will cause an exception to be thrown:

Microsoft.FSharp.Core.MatchFailureException: The match cases were incomplete
This stands in stark contrast to a bunch of if..else statements where one can ‘fall out’ and potentially leave the program in an unknown state.

Speaking of state… The match construct also frees us from having to manage our match state manually.

No temporary variables are created by the programmer – we don’t even explicitly store the value we’re matching!
Let’s say we have this C# code:

if(predicate1)
{	
       if(predicate2)
       {		
              predicate1and2action();
       }	
       else
       {		
              predicate1action();
       }
}
else if(predicate2)
{	
        predicate2action();
}

That is a lot to think about and in complicated cases it can difficult to get this right.

We have multiple exit points far apart in the function and it can be difficult to reason about the program just by looking at it. Compare with pattern matching:

let orFunc x y = 	match x, y with	
 | true, true -> true 	
 | true, false -> true	
 | false, true -> true 	
 | false, false -> false;;

The inline predicates and lack of nesting make clear the purpose and result of the function for all the possible inputs.
Pattern matching is also a nice way to encapsulate behaviour for injection into other parts of a program. The flow control including any side effects is captured and can be passed around as an object into a higher-order dispatcher (perhaps another matcher!). Because the continuations are only executed when the pattern is matched, passing around the matcher is efficient as the evaluation of the continuations is lazy.

F# and Haskell have really nice syntax for pattern matching and when combined with strong type inference, pattern matching becomes a standard way to express behaviours in a functional program.
For those of us using C#, C# 3.0 gives us the nicer ‘lambda’ syntax for anonymous methods and so makes it feasible to implement a simple pattern matching class.
That’s exactly what I have done.

The source is available on GitHub here.

You can match literals:

Matcher<int>	
.Match(5)	
.With(5,x=>System.Console.WriteLine("5!"))
.Go(); 

Here, 5 is the pattern being matched and x=>System.Console.WriteLine(“5!”) is the continuation function.
Matcher will throw an Exception if provided a value that matches no pattern.
(The implementation uses .Equals() to determine object equality, so if you want to use literal matching in C#, you should use it only with a proper immutable data type that overrides .Equals())
If you want to create a ‘catch all’ pattern, you can use Else(). This pattern will be checked only after all other defined patterns have been examined.

Matcher<int>	
.Match(5)	
.With(5,x => System.Console.WriteLine("5!"))	
.Else(x => System.Console.WriteLine("Not 5!"))	
.Go(); 

These are all well and good, but the continuation functions all have side effects. What if we want to be purely functional? We would need to return a value from our matcher…

bool result = Matcher<int,bool>				
.Match(6)				
.With(5,x => true)				
.Else(x=>false)				
.Go();

Now we can at least use a matcher as the entire body of a method. However, we’re still matching literals, both in how we retrieve the value, and our pattern for matching it.
This isn’t necessary at all – in fact this is all just sugar. Both the value accessor and pattern match predicate are functions themselves, the type signatures tell the story:

public static Matcher<T,TReturn> Match(Func<T> accessor) 
public Matcher<T,TReturn> With(Func<T,bool> predicate,Func<T,TReturn> continuation)

At least now we can do this:

public int RecursiveFunction(int y)
{	
return Matcher<int,int>		
.Match(y)		
.With(x=> x > 0, x=> RecursiveFunction(x - 1))		
.Else(x=> x)		
.Go();
}

Now we’re talking!
Check out the unit test project for some more code samples.

(This blog post was written on the plane from San Francisco to Melbourne but I didn’t get a chance to post it until Christmas Day, so Merry Christmas everyone!).

Tagged , , , , ,
Follow

Get every new post delivered to your Inbox.

Join 180 other followers