Lately I am trying improve my programming by following some Katas. One of the things, I have been trying to learn was Functional Programming. So I decided to spend more time and try to write the same code I write in C# to see how can I adopt and learn faster. So in this blog, we will look at a small program I was trying to do in C#
1. Using third party control:
To use third party control, you do exactly same as you would do in C#, add the reference and then instead of using ‘using namespace’ in F# you would open the namespace to use in the code. In this example I am using bcParser.Net.dll to evaluate arithmetic expression. So the open would look like something like the following
2. Working with a class:
Now that we added reference to the namespace we need to instantiate the class and add arithmetic expression to it to use it. For our example, our expression is “1+2” and expect the result to 3. To instantiate the class
let mathParser = MathParser()
now that mathParser is the instance of the class, we need assign the expression to mathParser expression member variable. This is done little different than C#. In C# we will do some thing like the following
mathParser.Expression = “1+2”
but in F#, you have to do the following
mathParser.Expression <- “1+2”
3. Printing the result:
Now that we have the expression set, we need to evaluate and print the result to console. This part is very simple
printfn “%s” (mathParser.Value.ToString())
make sure you put the whole thing parenthesis otherwise you will get compiler error.
One thing I noticed while using F#, the compiler errors are so explanatory, you will able to figure out what were you doing wrong in the code.