Values, Bindings and Basic Types
3.1 let Bindings
let x = 42 // immutable binding (type inferred: int)
let name: string = "Ana" // explicit type annotation
let pi = 3.14159 // float (System.Double)
// x <- 43 // error: x is not mutable
let mutable counter = 0 // explicit mutability
counter <- counter + 1
let total = // blocks are expressions; the last line is the value
let a = 10
let b = 20
a + b // 30
let x' = x + 1 // shadowing/new names: ' is valid in identifiers
let ``my weird name`` = 1 // double-backtick identifiers allow spaces3.2 Primitive Types
42, 0xFF, 0b1010, 1_000_000 uint32, byte, sbyte, int16 42u, 42uy, 42y, 42s float (double) 3.14, 1e10 float32 (single) true, false
"text", """triple-quoted""", @"verbatim" F# never converts numeric types implicitly: 1 + 2.0 is an error. Use float, int, decimal, etc.
let a = 7 / 2 // 3 (integer division)
let b = 7 % 2 // 1
let c = 7.0 / 2.0 // 3.5
let d = 2.0 ** 10.0 // 1024.0
let e = float 7 / 2.0 // 3.5: explicit conversion (no implicit numeric conversion!)
let f = int 3.99 // 3
let g = int "42" // 42 (parses; throws on invalid input)
let ok, value = System.Int32.TryParse "42" // tuple return for out parameters
let big = 2I ** 100 // big integer
let m = max 3 7, min 3 7, abs -5, sqrt 16.0, round 2.5 // (7, 3, 5, 4.0, 2.0)
let isEqual = (1 = 1) // = is equality; <> is inequality
let notEqual = (1 <> 2)3.3 unit and Side Effects
let sayHi () = printfn "hi" // takes unit, returns unit
sayHi ()
let result = ignore (1 + 2) // ignore discards a value (returns unit)
do printfn "a do-binding runs a side effect"