Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

Values, let Bindings, Scope and Mutability in F#

Understand F# let bindings: immutable values, type inference and annotations, shadowing, scope and nested lets, naming rules, and when to use mutable and ref cells.

The keyword you will type most in F# is let. It binds a name to a value. This is different from the "variable" you know from other languages: a binding does not name a box whose contents change, it names a value. This lesson explains what that means, how types are inferred, how scope and shadowing work, and the safe, explicit way to use mutation when you need it.

Binding a name to a value

FSHARP
let age = 36
let name = "Ada"
let isStudent = false
let height = 1.68

The compiler infers int, string, bool and float. In FSI the result looks like val age: int = 36. A binding is a one-line definition: the name, =, the value. There is no semicolon, no var, no type keyword.

Trying to rebind in the same scope is an error in a file (and a surprise in FSI, where it works because each line is a new scope):

FSHARP
let x = 5
let x = 6     // error in a module: duplicate definition of 'x'

Type annotations

Usually you let inference work. When you want to document intent, fix a type, or choose between numeric types, annotate with a colon:

FSHARP
let count: int = 10
let ratio: float = 0.5
let big = 10L            // int64 via suffix
let small = 10uy         // byte via suffix

Annotations are also how you resolve ambiguity. Inference reads code top to bottom, so sometimes it needs help:

FSHARP
let length (s: string) = s.Length   // without the annotation the compiler cannot know s has Length

Naming rules

  • Use camelCase for values and functions (userName, totalPrice).
  • Use PascalCase for types, modules and union cases.
  • Names can contain letters, digits, _ and ' (a prime), so x' and total2 are valid.
  • To use a reserved word or a name with spaces, wrap it in double backticks, as in the code block below. This is mainly useful for test names.
FSHARP
let ``total cost`` = 100
  • Use _ to ignore a value you must bind but do not need: let _ = printfn "side effect".

Scope and nested bindings

A let inside a function is visible only below it, within that function. Indentation creates the nested scope:

FSHARP
let circleArea radius =
    let pi = 3.14159
    let squared = radius * radius
    pi * squared

pi and squared exist only inside circleArea. The last expression is the function's result; there is no return keyword.

You can also write let ... in ... on one line, which you will sometimes see in older code or inside quick expressions:

FSHARP
let result = let a = 2 in let b = 3 in a * b   // 6

Prefer the multi-line form in normal code.

Shadowing

Inside a function (not at module level) you can bind the same name again. The new binding shadows the old one for the rest of the block. The old value is not changed; it is just hidden:

FSHARP
let process input =
    let input = input.Trim()          // new "input", trimmed
    let input = input.ToUpper()       // another one
    input

Shadowing is handy for step-by-step cleaning of a value, but do not overuse it: too many layers of the same name hurt readability.

Immutability, shown

FSHARP
let a = 10
let b = a + 1
// a is still 10; b is a new value

There is no way to "update" a. If you want a changed version of a value you create a new one. This matters most for collections: List.append returns a new list and leaves the original untouched. The next chapters show that this is efficient because immutable structures share their parts.

Mutable variables

Sometimes mutation is the clearest answer: a loop counter, a performance-critical buffer, interoperability with .NET APIs. Declare it with mutable and change it with <-:

FSHARP
let mutable counter = 0
counter <- counter + 1
counter <- counter + 1
printfn "%d" counter     // 2

Two details to remember. Assignment uses <-, while = is comparison in an expression (counter = 2 is a bool). And a mutable local value cannot be captured by a closure (a lambda that uses it), which the compiler rejects. In that case use a ref cell:

FSHARP
let total = ref 0
[ 1; 2; 3 ] |> List.iter (fun n -> total.Value <- total.Value + n)
printfn "%d" total.Value     // 6

ref creates a heap-allocated mutable box. Read and write it through .Value. (Old code uses !total and :=; they still compile but are discouraged.)

Treat mutation as a last resort. Many loops with a mutable accumulator become a single List.sum, List.fold or List.map call, which you will learn in Collections.

Constants and literals

For a true compile-time constant use the [<Literal>] attribute with an UPPER or Pascal name. Literals can be used in patterns, which you will rely on later:

FSHARP
[<Literal>]
let MaxUsers = 100

Compare with a C# stand-in

This C# program mirrors let bindings, shadowing (via nested scopes) and the mutable counter. The first TryIt shows that in C# the default is mutable, while const and readonly are the exceptions: the reverse of F#.

C# C# stand-in: values and a counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: shadowing by sequential cleaning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • Using = to assign: x = 5 compares; you want x <- 5 (and x must be mutable).
  • Redefining a name at module level and getting "duplicate definition".
  • Forgetting that an inner let is not visible after the function ends.
  • Reaching for mutable first. Try a collection function first.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the effect of let x = 5 followed later by trying to change x with x <- 6?

    Let bindings are immutable unless declared with mutable. Assignment to an immutable value does not compile.
  2. 2. How do you write an assignment to a mutable value?

    The arrow <- assigns. A plain = in an expression is a comparison.
  3. 3. What is shadowing?

    A new let with the same name hides the earlier one; the old value is not modified.
  4. 4. Why might you need a ref cell instead of let mutable?

    Lambdas cannot capture mutable locals, but they can capture a ref cell and update its Value.

Summary

  • let name = value binds a name to an immutable value; the type is inferred.
  • Annotate with : type for clarity or to help inference.
  • Inner lets create scope; the last expression is the result; shadowing hides earlier bindings.
  • Use let mutable with <- when mutation is truly needed, and ref cells when a closure must change a value.

Next: Basic types: numbers, bool and char