It may look like F# is a dynamic typed language like JavaScript, Ruby, or Python. In fact, F# is statically typed like C#, C++, and Java. It uses type inference to figure out the correct types. Type inference is a technique which is used to automatically deduce the type used by analyzing the code. This approach works remarkably well in nearly all situations. However, there are circumstances in which you as a programmer need to make clarifications to the compiler. This is done using type annotations, a concept we will look into in the following sections.
Let's explore some of the built-in types in F# using the REPL.
> let anInt = 124;; val anInt : int = 124
This means that F# figured out the type of anInt
to be of type int
. It simply inferred the type on the left-hand side to be of the same type as the right-hand side of the assignment. Logically, the type must be the same on both sides of the assignment operator, right?
We can extend our analysis into floating point numbers as shown in the following lines of code:
> let anFloat = 124.00;; val anFloat : float = 124.0
Because of the decimal sign, the type is determined to be of type float
. The same holds true for double
as shown in the following lines of code:
> let anDouble : double = 1.23e10;; val anDouble : double = 1.23e+10
For other types, it works in the same way as expected as shown in the following:
> let myString = "This is a string";; val myString : string = "This is a string"
All the primitive built-in types, except for unit
, have a corresponding type in .NET.
The following table shows the most common primitive types in F#:
Type |
.NET type |
Description |
---|---|---|
bool |
Boolean |
true or false |
byte |
Byte |
0 to 255 |
int |
Int32 |
-128 to 127 |
int64 |
Int64 |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
char |
Char |
0 to 18,446,744,073,709,551,615 |
string |
String |
Unicode text |
decimal |
Decimal |
Floating data type |
unit |
- |
Absence of an actual value |
void |
Void |
No type or value |
float |
Single |
64-bit floating point value |
double |
Double |
Same as above |
Note
For more information and all type you can visit http://msdn.microsoft.com/en-us/library/dd233210.aspx.
There are also other types that are built into the language which will be covered in more detail in the next chapter, such as lists, arrays, sequences, records, and discriminated unions.