Saturday, December 17, 2011

F# ≥ C# (Concise Syntax)

Constant customer feedback shows F#'s code is more concise, which improves their productivity, but did not give any detailed information. I was always wondering what could make F# concise.


  • Implicit constructor and parameter


Today I declare a class and suddenly realize there is no constructor defined. The constructor is defined between two brackets as shown below:

type Account(name, socialNumber) = ...

the nice part is not just saving some typing, but also the value can be referenced from the code inside type definition. I would say this design is very considerate because those constructor parameters are mostly needed in other parts of the type definition. So instead declaring a class field and expose the field as a property, F# can expose property in one shoot.

type Account(name, socialNumber) =
    member me.Name with get() = name               //expose parameter
    member me.SSN with get() = socialNumber
    member me.Print() = printfn "%s - %d" name socialNumber   // access parameter from constructor


  • this keyword

If you take a closer look at the code above, you might scratch your head wondering what "me" is. Is this VB? No. In F#, you can use any identifier as "this" pointer. In the code above, I use "me", I saw some code use "x". For people from other background, such as VB, class definition is more friendly.

Do forget the "Automatic Generalization" feature, it can save many type definition code or even no need for "var".

Facing a long list of tasks when you open your computer in the morning, are you thinking about improve your productivity and can go home earlier?  :-)




No comments: