As already mentioned, F# is a typed functional language, by which I mean that types of allvalues are determined during the compile-time. However, thanks to the use of a
,the types are explicitly specified in the code very rarely as we will see in the following examples.The type inference means that the compiler deduces the type from the code, so for examplewhen calling a function that takes
as an argument and returns
as a result, the compilercan infer the type of the variable where the result is assigned (it has to be
) as well as thetype of the variable that is given as an argument (it has to be
). Basic data types (aside from astandard set of primitive numeric and textual types that are present in any .NET language)available in F# are tuple, discriminated union, record, array, list, function and object. In thefollowing quick overview, we will use the F# interactive, which is a tool that compiles andexecutes the entered text on the fly.The F# interactive can be either used from Visual Studio or by running the
from theF# installation directory. In the whole article series we will also use the F# lightweight syntax,which makes the code white-space sensitive, but simplifies many of the syntactical rules. Toenable the lightweight syntax enter the following command in the FSI:
The double semicolon is used as the end of the FSI input and sends the entered text to thecompiler. This allows us to enter multiple lines of code in a single command. With a fewexceptions (mostly when showing a declaration of a complex type) all the code samples in thisarticle are written as commands for FSI including the double semicolon and the result printed bythe FSI. Longer code samples can be entered to FSI as well - just add the double semicolon toterminate the input.
F# Data Types Overview
The first example demonstrates constructing and deconstructing a tuple type. Tuple issimple type that groups together two or more values of any (possibly different) types, forexample
> let tuple = (42, "Hello world!");;val tuple : int * string> let (num, str) = tuple;;val num : intval str : string
As you can see, the compiler deduced a type of the expression that is present on the right side of the equals sign and the F# interactive printed the type, so we can review it. In thisexample the type of a first element in a tuple is
and the type of the second element is
.The asterisk denotes that the type is a tuple. Similarly, you can define a tuple with more thanthree elements, but the type changes with the number of elements in a tuple, which means that tuples can't be used for storing an unknown number of values. This can be done using lists orarrays, which will be discussed later.