SIGN UP MEMBER LOGIN:    
ARTICLE

Variables and Function in F#

Posted by Dhananjay Kumar Articles | F# January 13, 2011
This article shows how to define variables and functions with the let construct in F#.
Reader Level:

Variables and functions are both defined with the let construct in F#.

Defining a integer variable 

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

In the above snippet we defined an integer variable in F# with let constructs. In F# types automatically get inferred. In the preceding declaration, the type is automatically inferred as int. 

Output

1.gif
 
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

2.gif

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
 
3.gif

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor