New F# edX course

Just wanted to share this new edX course on F# really quick:

Posted in Computer Science, F#, Functional Programming, Media

Why I don’t like .NET generics

This is just a quick rant: I don’t particularly enjoy the generics concept as realised in .NET. It feels like a half-baked, less powerful and at times restraining flavour of C++ template meta-programming. If you have a C++ background and first start using C# .NET generics, you will inevitably make the same mistakes I did.

1. Generics are resolved at run-time

That’s right. Generics cannot be used for code generation, as they are resolved at runtime. Sure, the compiler will attempt to figure out what the heck you are doing but god forbid it fails to see just how what you are doing might work, then it will refuse to compile your code.

Side-effect of this: You cannot inherit from a generic type parameter. The following is actually illegal:

2. The compiler just cannot impose restrictions on generic type parameters for you

The following is not valid C#:

It will fail to compile with a rather confusing error message:

Why does the C# compiler do this? It has no idea which specialization of Min I am going to use. Why not wait and see? The following is a valid variation of the above:

If T implements neither IComparable<T> nor IComparable, a runtime error is thrown. The question which arises from this is: why doesn’t the compiler know this? Or even better, why can’t I even use the generic type constraints to make the compiler know that I can actually compare T in this fashion? Again, the following is not valid C#:

Guess what, though. This mess actually compiles and will run:

If you invoke Min() with two objects that are not comparable, then a RuntimeBinderException is thrown. So: if generics are resolved at runtime, why the fuck can’t it behave like dynamics?


Posted in .NET, C++, Meta programming

Why writing a parallel interpreter might be a bad idea

When faced with the challenge of designing a domain-specific language for validating a document and enforcing certain behavioural policies on it, performance springs to mind. Documents that mandate such sophisticated validation set-ups typically come with a comparatively large set of fields that may change and in turn effect more changes. Since validation (usually) is a strictly functional process (i.e. validate is a function that takes an input and gives its validity), an expression-based language seemed like the most logical choice.

1. Expressions and the stack

If the most abstract type of node in an object graph modeling the syntax tree is an expression (i.e. there are no statements and no blocks), we don’t need a stack. If you don’t need a stack, things become very easy to parallelize. The consumers of the stack do intrinsically rely on a certain order of execution. If you can not rely on a pop yielding the value that you pushed just before, things get messy and (rightfully) break.

When looking at programs as functions, we do no longer have this problem. Take any binary expression (e.gyou . and) and make its operands expressions, and you’re looking at a function that takes two expressions and gives a boolean; this corresponds to prefix notation (i.e. and(1, 0) = 0).

2. Observable<T> vs Future<T>

The first problem with the above model arises when you need to react to specific events (e.g. if X occurs then do Y). In this domain, the most common event one needs to react to is the change of some property (field) of the document. This is where the absence of a stack starts to create some unnecessary roadblocks. We would probably like to be able to model something like this:

We subscribe to the value of Field_A, if we observe a change and the state of Checkbox_A is checked, then we want to set Checkbox_B to checked as well. The problem that might not be immediately apparent is the transport of the value of Field_A to the observer of the former. We either need a named value (some structure akin to the free store), or we need a stack so that we can pop the observed value as needed.

If, however, we make a function ChangedValueOf which promises to return a T, we can rewrite the above algorithm like this:

We no longer have a problem. Of course, writing policies like this will quickly get ugly, which is why our parser should be able to take a prettier (less deeply nested) representation of the above and build the AST accordingly. The invocation of Equals equality check function becomes the continuation of the Future<T> given by ChangedValueOf. The trick is to block the future until the value actually changed. Since we are working with snapshots of the document (in order to avoid progressively polluting the rulesets input with changes made as a result of its own evaluation), this becomes difficult to model.

So what do we do?

3. Ad-hoc rewriting the AST

The only solution I could come up with is rewriting the AST as-needed. We need to be able to take any expression and change it on-the-fly.



Posted in Computer Science, Functional Programming

Setting up a RPi using Synology for extended storage

Today I decided that it would be a good idea to repurpose my 2011 Raspberry Pi as a lean web- and Linux-development system. I also decided that it would be a good idea to store any data off-device on my Synology NAS. The RPi was outfitted with Raspbian using the NOOBS Setup toolchain. After initial setup I disconnected the RPi from all input peripherals and the screen and hooked it up to my switch instead.

Step 1.) Networking setup

The RPi will by default use my router’s DHCP server to find its IP. This is not strictly what I want, as I sometimes use a different network setup and would prefer to have the RPi to have a static IP in my reserved server range (, where my Synology amongst other devices is also situated.

Quickly asserting that the RPi can see the DS:

I continued to configure the interfaces (5):

Step 2.) Setting up everything on the Synology side of things

Next, I set up a new share and a user in my Synology DS (cleverly called “rpi”):

2015-04-08 Synology Setup

Step 3.) (Auto-)Mounting the network share on the RPi 

And finally, I mounted the CIFS share, following the steps described in this Synology wiki article. Which basically boiled down to:

This fstab (5) configuration. The ultimate result can be marvelled at here:

2015-04-08 RPi Synology Link


Next steps:

  • Setting up nginx and various interpreters for languages (PHP, Python, etc.) via FastCGI, running on the RPi using the synology-store for storage
  • Setting up redis, MySQL and various other RDBMS on the Synology – or perhaps a second RPi
  • Start playing!
Posted in Computer Science, Media

[Project Euler 6]: Solution in F#

Here’s my solution for the sixth Project Euler problem. I do not really see how this is hard. Perhaps there is a smarter way of solving this? Looking forward to your feedback.

I just remembered that there is a formula for finding the sum of a series of natural numbers. I am going to try and see if I can work with that to find a more efficient solution.

Posted in Functional Programming, Project Euler

[Project Euler 5]: Solution in F#

So here’s my brute force solution for the fifth Project Euler problem in F#.

I did not really understand this problem. Perhaps certainly there is a more efficient solution. Either way, the code works 🙂

Posted in Functional Programming, Project Euler

[Project Euler 4]: Solution in F#

Today, I’m going to attempt to solve the fourth Project Euler problem in F#. I only have about 15 minutes before I need to get back to doing something different, so I’ll probably just leave this post hanging until I find time to advance the code.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

So, the first function I am going to write is “palindrome of n” (i.e. produce 9009 from 90):

The largest product of any 3-digit number is 999² = 998001; this means that the upper bound of palindromes we need to test against is 997799. So here’s the generator for the series of palindromes we need to factorize:

Update 2015-05-02: Finally found some time to finish this. I basically wrote a function that will spit out all factors of n where every factor is element of the set {100..999}. Here goes:

I then wrote another function which applies threeDigitFactors to all palindromes and finds the largest sum of factors:

Which yielded:

I do realize that this is inefficient, but I am not too maths-savvy to come up with a better solution at this point.

Posted in Functional Programming, Project Euler

[Project Euler 3]: Solution in F#

Before heading back into the real world, I am going to attempt to solve the third Project Euler problem.

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

I currently have no idea how to implement prime decomposition efficiently in any language. I do however know that n is prime if not a multiple of any number [2..sqrt(n)] , so this seems like the most logical starting point.

I have had quite a hard time trying to implement [2 .. sqrt n], let me know if there is a better way of doing this. Next, I wrote a function to find all the factors of a number:

Originally, I had attempted to use this directly with the “isPrime” function in order to yield the largest prime using Seq.max:

This kept resulting in System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.  because it naturally attempted to check all of the resulting factors for (a) their primeness and then find out the maximum value. So I went and wrote another function “factorsReverse”, so that we may use Seq.find (which returns as soon as the given _ -> bool evaluates to true):

Runtime was immensely reduced and there were no more Out-of-Memory exceptions!





Posted in Functional Programming, Project Euler

[Project Euler 2]: Solution in F#

In continuation of my F# efforts, I am going to try and solve the second Project Euler Problem. Here’s the problem:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Just like for problem 2, the last sentence of the problem is basically the final code:

This was fun to implement. Originally I had made a recursive sequence generator for the fibonacci series (the rest of the code was basically the same however).  Seq.unfold basically unfolds a given generator (which in this case is a lambda expression) into a sequence given initial state (0, 1).


Posted in Functional Programming, Project Euler

[Project Euler 1]: Solution in F#

Whenever I am trying to learn a language that I have no clue about, I like solving the Project Euler problems with it. I’m going to share my solutions here and hope that I can either help somebody understand the problem / solution or the language or if someone gave me feedback on how to improve!

The problem I’m going to solve in this post is “Problem 1: Multiples of 3 and 5“.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

Basically, the last sentence “sum of all multiples of 3 or 5 below 1000” already seems like it could be actual source code of a rather expressive programming language. What we have here is a set of numbers where every number is divisible by 3 or 5. In order to determine whether a number is divisible by 3 or 5 we need to write ourselves a function that can determine whether a number is divisble by another number. We can then use this function to build a new function that will tell whether its input is divisible by either 3 or 5.

Based on this we then get the sequence “all multiples of 3 or 5 below 1000”:

Executing the FSX script yielded the correct answer:  val sumOfMultiples : int = 233168. In retrospect I would probably have preferred to have a generalized isMultipleOf3Or5 accepting a list for the “d” parameter. I am quite satisfied with my first F# program taking me less than 5 minutes to get correct, however.

On to the next problem!

Posted in Functional Programming, Project Euler