Variables in F#

In F#, variables are typically declared using let bindings. These can be mutable or immutable, with immutability being the default and preferred approach.

open System

[<EntryPoint>]
let main argv =
    // 'let' declares a binding (similar to a variable)
    let a = "initial"
    printfn "%s" a

    // You can declare multiple bindings at once
    let b, c = 1, 2
    printfn "%d %d" b c

    // F# has type inference, so it will infer the type of initialized bindings
    let d = true
    printfn "%b" d

    // Bindings declared without initialization are not allowed in F#
    // Instead, we can use the default value for a type
    let e = Unchecked.defaultof<int>
    printfn "%d" e

    // In F#, all bindings are immutable by default
    // To create a mutable binding, use 'let mutable'
    let mutable f = "apple"
    printfn "%s" f

    // You can change the value of a mutable binding
    f <- "banana"
    printfn "%s" f

    0 // return an integer exit code

To run the program, save it as Variables.fs and use the F# compiler (fsc) to compile it, then run the resulting executable:

$ fsharpc Variables.fs
$ mono Variables.exe
initial
1 2
true
0
apple
banana

In F#:

  • Variables are called bindings and are immutable by default.
  • Type inference is used extensively, but you can also explicitly specify types.
  • Multiple bindings can be declared in a single let statement.
  • Mutable bindings are possible but less common, following functional programming principles.
  • The <- operator is used to assign new values to mutable bindings.
  • There’s no direct equivalent to Go’s zero-value concept; instead, you typically initialize values explicitly or use Unchecked.defaultof<'T> for default values.

F# encourages immutability and functional programming paradigms, which can lead to more predictable and easier to reason about code.