Basics 02 - Basic Data Types and Signatures
Time to discuss the basic data types and signatures.
Learning-FSharp/Ch02-DataTypesAndSignatures/Program.fs
Check out all the comments that are placed in the source file.
Key Ideas
Variables (values, actually) and functions are defined using
let
bindingsTo define a variable:
let variableName = ...
To define a function:
let functionName param1 param2 = ...
Variables created with
let
binding are immutableUse
let mut
binding to create mutable variablesTo define a mutable variable:
let mut varName = ...
To mutate the value:
varName <- ...
Immutability may seem like an odd idea, especially if you are coming from C++/C#/Java world
Functional programming is mostly done with immutable variables; you will learn as we proceed
F# compiler does an amazing job at identifying the types of variables
In most cases decorating a variable name with the type (aka type declaration) isn't required
The absence of type declaration with a variable doesn't mean it is type-less; F# is strictly typed
The following statement results in the creation of an immutable
int
variable with value 10; the type is auto-detected based on assigned value:let x = 10
To include type declaration:
let y: int = 10
Signed integer data types:
sbyte
,int16
,int
,int64
Unsigned integer data types:
byte
,uint16
,uint
,uint64
Boolean data type:
bool
Char and string:
char
andstring
32-bit floating type:
float32
orsingle
64-bit floating point:
float
ordouble
Generic type:
'a
or'b
or'T
; more on this laterAbsence of data:
unit
C++/C#/Java programmers tend to think of
unit
as void, which isn't the best ideaThink of
unit
as an empty placeholderThe
unit
data type has one possible value:()
Function signature:
input type -> return type
A function with more than one parameter:
type1 -> type2 -> type3 -> return type
A function with unit input:
unit -> return type
A function with unit output:
input type -> unit
A function with unit input/output:
unit -> unit
Both these functions have the signature:
int -> int -> int
No types declared:
let add x y = x + y
With types declared:
let add (x: int) (y: int) : int = x + y
Function call:
let varName = funcName param1 param2 ... paramN
Assume a function named
F
with signatureunit -> int
let varName: int = F ()
results in the invocation ofF
; The()
inF ()
isn't similar to calling a void function in C++/C#/Java; Remember()
is a value of type unit;()
is the parameter passed toF
If you have reached so far, congratulations.
Keep reading!