Variables and Function in F#

No.of Views1165
Bookmarked0 times
Downloads 
Votes0
By  Dhananjay Kumar   On  13 Jan 2011 09:01:40
Tag : F# , General
Variable and functions both defined with let construct in F#.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Variable and functions both defined with let construct in F#.
Defining a integer variable

let a = 2;
 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 

Image Loading

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 

Image Loading

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 

Image Loading

Hopes help and thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
Dhananjay Kumar
Occupation-Software Engineer
Company-Infosys Technolgies,Pune
Member Type-Gold
Location-India
Joined date-20 Jul 2009
Home Page-http://dhananjaykumar.net/
Blog Page-http://dhananjaykumar.net/
Dhananjay Kumar is Microsoft MVP on connected system. He blogs at http://dhananjaykumar.net/ . You can follow him http://twitter.com/debugmode_/ and reach him at dhananjay.25july@gmail.com
 
 
Other popularSectionarticles
    This is very basic article, which will give demonstration on how to write first F# program
    Published Date : 18/Jun/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top