Ksunair’s Weblog

Just another WordPress.com weblog

Posts Tagged ‘addition’

F# Baby Step – 1

Posted by Unni on August 15, 2008

First think you need to do is to install F# in your computer (OS X or Windows). I am not going to explain how to install F# because the instructions at F# web site is very good source.

Once you installed you would see under Start-> Programs -> Microsoft Research F#

Something like the following. For our initial learning process I am going to stick to the first option F# Interactive (Console).

Let us write our first code. Normally people write “Hello World”, but I am not, I am going add two integer numbers. With this we can learn how to assign values to variables and how to perform an addition operation. Following picture shows the code and the result.

Adding 2 numbers in F#

Adding 2 numbers in F#

Each statement is seperated by ;; and each assignment uses ‘let’ keyword followed by variable name and then the value. One interesting part about the assignment statement is that the type. You didn’t declare the type of the variable but it was inferred from the value on the right hand side. In the first assignment the value is 3 and it is inferred as integer. That is what shown right below the let statement.

The line following let a = 5;; is val a : int, it means value a is of type integer. The same applies to the next let statement. The arithmatic statement

let c= a + b;;

also inferred the type based on the value of a and b and in this case value of c is integer. Let statement only created the assignment of the arithmatic operation but it didn’t really excute the statement. So to get the result you need to issue the last statement that is

c;;

this basically returns the value of c. I still need to learn some more basics of this assignment and operations.

Just for fun try

>3 + 4.0;;

it will fail. F# doesn’t do any automatic boxing and unboxing. So in this case, we are trying to add int with float and F# will throw an error. If you want to fix this, you need explicitly make this type same type like following

>3 + int 4.0;;

Advertisements

Posted in Introduction | Tagged: , , | Leave a Comment »