Simple Functional Programming in C#

Some of the greatest crimes in modern computing are committed in the name of good object-orientated abstractions. Over time, a code base gets so polluted with abstract classes, factories and heavy dependencies on frameworks that a lot of it ends up serving as boilerplate to work around the rest. I’ve spent the last few months learning Haskell (A pure functional language) and Go (An imperative language that allows OO and functional styles) and it’s led me to the conclusion that John Carmack is right, sometimes all you really need is a function.

Go’s approach to OO struck me as very interesting because instead of complex class hierarchies they took a very simple approach and allowed you to associate a function with a type. There’s no this keyword, you assign the type a name and use that to access it’s properties. Here’s a very simple example:

Note: Unused variables are compile-time errors in Go, hence why this is much simpler than the upcoming C# examples.

We can do something similar in C#. Here’s a very simple OO example in C#. In pure OO, an object is a bundle of state and methods that operate on that state so I’m going with a contrived sample that demonstrates this.

Now lets look at the functional solution:

Note on line 2 we’ve given Tuples of type <string, string, int> the alias of Person. Since System.Tuple is a class, we create our Person tuple almost exactly the same way as our OO solution. The biggest difference is that there is no maintained state. Our CompareAge function takes two Person tuples and computes the required value. There’s also a lot less worrying about encapsulation, since we can explicitly see that our people tuples only exist in the scope where we create them.

I’ll expand on this post in the future with some more example of how aliasing types in C# can be used to write concise functional code. If you’d like to try this out, have a go at aliasing a list of Persons and writing a function that iterates over them and returns the total age of everyone (this is a classic example of a functional fold operation!)

I’m trying a more lean, agile approach to blogging because the tax on adding links and sources with my limited free time is too great and I don’t want to stop completely. If you want me to expand on anything in this post feel free to leave a comment or drop me a line and I’ll try my best.

Advertisements

4 thoughts on “Simple Functional Programming in C#

  1. How about an example for the Go version? Do you use GetName(somePerson) or somePerson.GetName(), or what?

    Certainly the second example is a lot shorter, but it’s also just a 3-tuple by another name. Writing somePerson.Item3 instead of somePerson.Age is not going to go over well with the rest of the team, and they will eventually start cursing you for the order of the properties.

    Perhaps a different example would illuminate the point better, such as a recursive functions with immutable state vs iterative functions with mutable state.

  2. Yeah I do wish that C# had named tuples like Python has. The main point here is to answer the question of “Sure this functional stuff sounds cool, but how can I easily create methods for stateful objects without classes?”. I won’t be covering recursion or mutable vs. immutable because:

    a) C# is not a functional programming language so recursion shouldn’t be encouraged over iteration.
    b) mutable vs. immutable is only relevant when values are immutable by default, and in C# they are not. Anything that can be made immutable at compile time should be regardless of programming paradigm. Resharper does a lot to steer programmers in this direction thankfully.

    I’m well aware it’s just a tuple in the second example, that’s the beauty of it 🙂 I’m not trying to demonstrate how functional can save you LoC but it can save an awful lot of typical OO baggage associated with encapsulation,

    I’ll expand on the Go example when I get time hopefully. For now I’d suggest reading this: http://nathany.com/good/. Thanks for the feedback, I’d edit this and address all your points soon 🙂

  3. Sure, C# isn’t optimized syntactically for immutable state, but that doesn’t mean it’s not worth doing, like you mentioned with marking things final when possible. I don’t see any reason to say recursion isn’t viable in C#, with the exception of lacking tail call optimization.

    Also, I’d never heard of Python named tuples before. That looks pretty slick.

  4. I totally agree, I think immutable state should be used whenever possible which is why I don’t think it’s FP specific. FP and immutable state get mixed together a lot because many functional languages (Haskell, Scala and Clojure all do I think) are immutable by default and other posts get hung on on explaining why this is a good thing. I wish every day that C# values were non-nullable by default, it would save me a lot of checking strings for null using Code Contracts! http://msdn.microsoft.com/en-us/library/dd264808.aspx

    It’s very likely because I’ve written a lot of Python that I don’t think recursion should be used outside situations where it’s the obviously natural solution. If it did have optimization sure thing but it doesn’t, it won’t anytime soon (hint: ever) and outside of Project Euler solutions I rarely see any looping constructs in real code that would be better as a recursive functions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s