FSharp

Variables and Function in F#

Variable and functions both defined with let construct in F#.

Defining a integer variable

let a = 2 in a*a ; 
printfn "%d"a;;
System.Console.ReadKey(true);

In above snippet we defined a integer variable in F# with let constructs. In F# teypes autemetically get inferred. In above declaration type is automatically get inferred to int.

Output

clip_image002

The other way we can use language construct is

let var = expr1 in expr2

we can evaluate the expr1 in expr2. First expr1 will get assigned to var1 and then will get evaluated to expr2.

Defining a function

Below we are defining a function called sqr. It is taking one parameter and calculating the square of the input parameter.

let sqr n = n*n;;
let a= sqr 5;;
printfn "%d"a;;
System.Console.ReadKey(true);

Output

clip_image004

Above we saw the input parameter to the function got inferred to int. If we want to override default inference of the type then we need to explicitly tell the language about the type of input parameter.

Defining a function with explicit type at input parameter

let sqr (n:float) = n*n;;
let a= sqr 5.5;;
printfn "%f"a;;
System.Console.ReadKey(true);
 


Output

clip_image006

About Dhananjay Kumar

Dhananjay Kumar is Developer, Blogger , Speaker, Learner , Mindcracker & Microsoft MVP.

Discussion

Trackbacks/Pingbacks

  1. Pingback: Monthly Report January 2010: Total Posts 19 « debug mode…… - December 4, 2011

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 1,380 other followers

Tweets

Categories

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway. © Copyright 2012