Pages

Sunday, November 27, 2011

F# ≥ C# (Automatic Generalization)

In previous blog post, I use the Chain of Responsibility in a real world example. Five minutes later, I realize F# provides a very nice type generalization which makes my coding much easier than using C#.
let chainTemplate processFunction canContinue s =
    if canContinue s then
        processFunction s
    else s
the input parameter s is generalized so it is just a place holder. In my simple design pattern sample, the type is an integer.
// simple design pattern sample
let canContinueF _ = true
let processF x = x + 1
In the real world sample, s is actually a tuple type.

// real world problem 
let canContinueF (v,unitNameIndex) = v >= unit && unitNameIndex < unitNames.Length-1
let processF (x, unitNameIndex) = (x / unit, unitNameIndex+1)

F#'s automatic generalization feature almost makes my template pattern retired.

If you want to implement the same feature in C#, seems that you have to use generic function. It is true that C# can do the same thing, but readability and productivity will be much lower than the F# version. 

No comments: