Tuesday, 31. January 2012
Jan 31
This is yet another blog post in my Currying and Partial application series. This is what I have posted so far:
In this post I want to show you a way to simulate type classes in C# and F#. Type classes are this wonderful feature in Haskell which allow you to specify constraints on your polymorphic types. We don’t have this in C# nor F#.
Let’s start with the following problem: We want to compute the sum of the squares of arbitrary numbers. We want to write something like this:

The problem is we don’t have a generic * function and of course we’d also need a generic + operator and maybe a generic zero. Obviously we need a constraint on the generic parameter T since + might not be defined for any type. So let’s define an interface for numbers:
Nothing special here, so let’s get straight to the implementation for integers and doubles:
So far so good. With this in our pocket we rewrite SumOfSquares() into this:
The trick is that we pass the concrete implementation as the first parameter into our function. This works exactly like a type constraint or as Simon Peyton-Jones would say: the vtable travels into the function. Notice that we don’t have access to the definition of in nor double. There is no way for us to express that int or double implement a number interface.
Now let’s try this out:
As you can see, this is perfectly type safe. We now have a way for poor man’s type classes in C#. Yay!
Now what has this to do with partial application? Let’s look at the same thing in F#:
We’re using a lot of partial application here. Exercise: Try to spot all the places.
Ok, you’re right. This post might be a little bit far away from the partial application stuff, but it’s still related. Somehow.
Tags:
C-Sharp,
Currying,
F#,
partial application,
type classes
Monday, 30. January 2012
Jan 30
In the last couple of days I started to write some posts about Currying and Partial application:
This time I want to show you how we can write a higher-order function which allows us to curry another function. Remember the multiplication function from the first post and it’s curried form:
Currying
The question is: how can we automate this transformation process? Remember we want to have the curryied form for partial application:
Let’s look at the signature of the desired Curry-function: in our case it has to take Func<int, int, int> and returns Func<int, Func<int, int>>.
If we generalize the ints to generic parameters and fix the signature then the implementation is trivial (Compiler Driven Programming). There is exactly one way to make this work:
The F# implementation does exactly the same, but without all the annoying the type hints:
Uncurrying
Of course you can undo the currying by applying a generic Uncurry-function:
And in F# this looks like this:
Libraries
Currying and Uncurrying are two very important concepts in functional programming so they are included in a couple of libraries:
- You can find it at the top of the Prelude in FSharpx (read more).
- You can find it in the Haskell Prelude.
- You can find similar functions in Scalaz.
- Adrian Lang wrote a library called partial-js which allows to do something similar in JavaScript.
Tags:
C-Sharp,
Currying,
F#,
partial application
Sunday, 29. January 2012
Jan 29
My last blog post was yet another introduction to Currying and Partial application. Now I want to put the focus more on the why part. Why do we want to have our functions in curryied form most of the time? This is the first part of a small blog post series and shows partial application in F# pipelines.
Using “Fluent interfaces” is a popular technique to write code in a more readable form. In languages like C# they also provide a way to create the code much faster. On every . we get IntelliSense and this gives us a “fluid” way of writing.
Let’s consider the following task: we want to compute the sum of the square roots of all odd numbers between 1 and 100. In C# we can use the LINQ method chaining approach in order to do something like this:

Now how does this look in F#? It’s basically the same. We replace every . with the |> operator and use the analogous Seq.* functions:

Oups! What happened here? The F# compiler noticed a type error. Math.Sqrt needs a float as input but we gave it an int. C# uses implicit casts between int and float so we didn’t noticed the problem there. Implicit casts are a little bit problematic, at least if you want to have proper type inference so F# doesn’t have this feature. No problem, we are programmers so let’s add the conversion manually:
Notice that float is a function from int to float and not a cast.
Now you might ask: how does this all relate to partial application? The answer is simple: In every pipeline step we use a higher-order function (Seq.*) and apply the first parameter with a lambda. The second parameter is given via the |> operator from the line above.

By applying our rule of thumb from the last post were are able to remove the x parameters:
Now let’s step back to C#. Keeping this knowledge in mind we try to apply the same rule in order to get rid of the x parameters:

Oups again! Now we see same error in C#. In this case it doesn’t know how to apply the implicit cast. As I said they are “problematic”, but we know how to fix this:
Tags:
Currying,
F#,
partial application
Friday, 27. January 2012
Jan 27
Today I had a conversation on twitter about partial application and type inference in F#. Partial application is a very important and useful concept and there are a lot of resources out there. Here is a short list of related material:
I promised to show a small sample and I hope this clarifies some of my points on twitter. Let’s consider a multiplication function in C#:
This function allows us to compute the product of two ints. But what can I do when I need a function which doubles its input? The solutions is easy: I just create a new function:
And when I need a function which triples its input? Same thing, just create another method. But can we do better?
Let’s transform the multiplication function into the curryied version. The transformation process is very easy once you see the pattern. It’s actually possible to write a function which curryies another function, but that’s something for another post. Anyway, here’s the curryied version:
It’s a little bit noisy with all the funky Funcs, but Ok. We can still write the double function in terms of multiply:
And of course we can use multiply directly (which might look a bit weird at first):
But we can also use it in another way, which we couldn’t really do before:
How cool is this? We just applied a single parameter and we got a new function without writing any method declarations. Unfortunately we wrote a lot of weird type declarations in order to get here, but hey.
Let’s move to a language which has type inference. Here’s the uncurryied version of multiply in F#:
The type signature tells us, that we have to give it a tuple of ints and then we get an int back. That’s exactly the same as in C#. Notice that we think about x1,x2 as only one parameter – a tuple. How can we get to the curryied form? It couldn’t be easier: just remove the parentheses and you’re done:
As you can see the type signature changes a little bit. The * is now just another arrow. This means we have basically the same as Func<int, Func<int, int>> but in a much nicer syntax. There is also another way to write this:
This looks like the C# version, but notice how nicely the arrows align to the type signature. If we want to use the multiply function than we can write something like this:
It’s also very easy to create partially applied functions:
And finally the point which made me write this post. There is a simple rule: whenever we have the same parameter as the last parameter of the left and the right side of a function definition, we can remove it. This leads us to:
Isn’t this beautiful?
Tags:
Currying,
F#,
partial application
Sunday, 22. January 2012
Jan 22
Legacy code is a problem in all languages, even F#. 
The super awesome Ilker Cetinkaya published an excellent article about “test implants”. I really recommend to read his post before you read this one. It’s a really well written story called “The quest of the test”.
I destilled his nice little story to this small F# code:
We have a function a that is part of a third-party API and a function b which is part of our own legacy code base. The problem is: we want to check that b has called a. without changing b’s signature. Ilker suggested to use a “test implant”. Let’s try to do something similar with our small F# code. Since we are in the land of functional programming our idea is to implant another function into b. So let’s rename b into b’ and add the implant to the parameter list of b’.
Of course we restore b’s behaviour by utilizing b’:
As you can see, we didn’t change the signature nor the behaviour of b. This is a typical refactoring in F#. The program runs as before. Now we want to write our test:
I hope you can see the similarity between this and Ilkers solution. The only difference is that we don’t use new constructors here. I really like this since it brings you one step further to nice functional design. What do you think?
Tags:
F#,
TDD,
Test Driven Design,
test implants
Monday, 16. January 2012
Jan 16
Jenkins is an extendable open source continuous integration server. In this blog post I show you how you can build FAKE’s Calculator sample with Jenkins. If you are familiar with Jenkins or Hudson then this should be straight forward.
Install Jenkins
Go to http://jenkins-ci.org/ and download/install Jenkins. In addition install the following plugins:
Create a new Task
Create a new “free-style” task in Jenkins:

Use git as the Source Control Management tool and configure the repo as following:

Configure the build step to run FAKE from the command line:

And finally configure the post build actions:

Running the build
If everything is setup correctly, then you should be able to start the build from the project page:

The output should look similar to this:

Tags:
CI,
Continuous Integration,
F#,
Jenkins
Wednesday, 19. October 2011
Oct 19
My last posts described some special monads in F#. The code is now part of a new project called FSharpx. FSharpx is a library for the .NET platform implementing general functional constructs on top of the F# core library. The idea is that we start merging all these nice little F# open source projects we have and put them under one umbrella.
The project is in an early phase, but it’s really starting to accumulate so much interesting stuff and the number developers who are contributing is rising.
Unfortunately the documentation is not that good at the moment and therefore I want to present a collection of articles which cover some of the related topics:
I also recommend you to checkout the test projects. You will find there a lot of interesting samples.
If you find more articles about FSharpx or related topics, then feel free to contact me. I will include them here and in the documentation of the project.
Tags:
F#,
FSharpx
Wednesday, 17. August 2011
Aug 17
In the last part of this blog series I showed how we can utilize the DistributionMonad in order to solve the famous Monty Hall problem. This time I want to show you how we can use it to solve some basic Texas hold’em poker questions.
We start by defining a model for poker in F#:
As you can see we model cards as tuples of a rank and a suit. The complete deck is just a combination of all ranks with all suits.
Now we need some additional helpers for the DistributionMonad, which will allow us to draw cards from the deck. You can find further explanations about these helpers in the excellent paper by Martin Erwig and Steve Kollmansberger called "Functional Pearls: Probabilistic functional programming in Haskell". Like the DistributionMonad itself, these helpers are already in the FSharp.Monad project and you get the bits from nuget.org.
Now we are ready to perform our first query. Let’s see how we can compute the probability of drawing the Ace of Clubs and the Ace of Spades:
But we can easily go a step further:
If you keep this model in mind you might come up with a poker odds calculator on a smart phone. This might be your chance to get rich.
Tags:
F#,
monad
Tuesday, 16. August 2011
Aug 16
In the last part of this blog series I showed a DistributionMonad, which allows to perform queries to probability scenarios. Today we will use this monad in order to solve the famous Monty Hall problem. This article is based on the excellent paper by Martin Erwig and Steve Kollmansberger called "Functional Pearls: Probabilistic functional programming in Haskell".
“Suppose you’re on a game show, and you’re given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what’s behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?”
[problem definition from Wikipedia]
Let’s start by modeling the first choice using the DistributionMonad:
As we can see the solution is 1/3 as we expected and if we don’t switch, we stay with these odds. But if we switch we might improve the probability for a car. Remember the host will always remove a Goat after your first pick. Let’s analyze the second pick if we switch:
| Car behind |
First choice |
Temp. Outcome |
Host removes |
Switching to |
Outcome |
| Door 1 |
Door 1 |
Car |
Door 2 |
Door 3 |
Goat |
| Door 1 |
Door 1 |
Car |
Door 3 |
Door 2 |
Goat |
| Door 1 |
Door 2 |
Goat |
Door 3 |
Door 1 |
Car |
| Door 1 |
Door 3 |
Goat |
Door 2 |
Door 1 |
Car |
If the Car is behind door 2 or door 3 the situation is symmetrical and therefor we can conclude, the following:
And if we run this, we get this nice solution:
Next time I will show how we can use the DistributionMonad to solve some basic poker scenarios.
Tags:
F#,
monad
Monday, 15. August 2011
Aug 15
In part I of this blog series I showed a simple InfinityMonad, which allows to treat special calculations as infinity and in the second part I showed the UndoMonad, which defines an environment which allows to undo and redo state changes.
This and the following posts are based on a famous paper by Martin Erwig and Steve Kollmansberger called "Functional Pearls: Probabilistic functional programming in Haskell".
Let’s start by looking at a small scenario:
This simple query calculates the probability of the event, that an dice roll gives a value greater than 3 and an independent coin flip gives “Heads”. In order to do this the DistributionMonad enumerates all possibilities and calculates the joint probability using the following formula:

If we want the nice syntactic sugar we can easily define a computation expression builder:
In order to allow easier access to our monad, we define some helper functions and basic distributions for fair coins and dices:
In the next part of this blog series I will show how we can utilize the DistributionMonad in order to solve the famous Monty Hall problem.
Tags:
F#,
monad