Data Types
Prerequisites: Values and immutability
Every value in F# has a type, known at compile time. The everyday types:
| Type | Example | Notes |
|---|---|---|
int |
42 |
32-bit integer |
int64 |
42L |
64-bit integer |
float |
3.14 |
64-bit floating point (called double in C#) |
decimal |
19.99m |
exact decimal, for money |
bool |
true |
true or false |
char |
'A' |
a single character, in single quotes |
string |
"hello" |
text, in double quotes |
unit |
() |
"no meaningful value" |
let count = 42
let big = 9_000_000_000L
let ratio = 0.75
let price = 19.99m
let isReady = true
let grade = 'A'
let greeting = "hello"
printfn "%A %A %A %A %A %A %A" count big ratio price isReady grade greeting
printfn "%s" (count.GetType().Name)
printfn "%s" (price.GetType().Name)
42 9000000000L 0.75 19.99M true 'A' "hello"
Int32
Decimal
%A shows each value the way you'd write it in code — note the L,
M, and quotes. Underscores in number literals are just for
readability. GetType().Name shows the underlying .NET type: F#'s int
is .NET's Int32.
Converting between types
F# never converts automatically. Use the conversion functions, which are named after the target type:
let a = 7
let b = 2.5
printfn "%f" (float a + b)
printfn "%d" (a + int b)
printfn "%d" (int "123" + 1)
printfn "%s" (string a + "!")
printfn "%M" (decimal a / 3m)
printfn "%c" (char 65)
printfn "%d" (int 'A')
9.500000
9
124
7!
2.3333333333333333333333333333
A
65
int 2.5 truncates toward zero, and int "abc" throws an exception —
you'll learn safe parsing with TryParse later.
unit
unit has exactly one value, written (). Functions that only do
something (like printing) return unit, the way void works in C-style
languages — except unit is a real value you can pass around:
let result = printfn "side effect!"
printfn "%A" result
side effect!
()
Common mistakes
- Writing
3 / 2and expecting1.5— both areint, so the answer is1. Write3.0 / 2.0. - Mixing
intandfloatin arithmetic (1 + 2.0) — a compile error; convert one side. - Using
floatfor money — usedecimal(19.99m) to avoid rounding errors.