ZetCode

F# variable scope

last modified December 2, 2026

In this article we look at where a name can be used in an F# program.

The scope of a name is the part of the program in which the name refers to its binding. F# uses lexical scoping: the scope is decided by the layout of the source code, not by the order of calls at run time. A name is visible from the line after its binding to the end of the block that contains it. How blocks are formed with let is covered in F# let bindings; this article applies the rules to functions.

Top-level and local values

A value bound at the top level of a script is visible in the rest of the file, including inside functions. A value bound inside a function is local to it.

local.fsx
let taxRate = 0.2

let priceWithTax price =
    let tax = price * taxRate
    price + tax

printfn "%.2f" (priceWithTax 50.0)
printfn "%.2f" (priceWithTax 120.0)

The function adds a tax to a price.

let taxRate = 0.2

The taxRate value is defined at the top level, so the function can use it.

let priceWithTax price =
    let tax = price * taxRate
    price + tax

The parameter price and the local value tax exist only inside the function body. Each call gets its own price and tax. Code outside the function cannot refer to them; using tax after the function fails with error FS0039, which says that the value is not defined.

λ dotnet fsi local.fsx
60.00
144.00

Nested functions

A function can be defined inside another function. The inner function is local to the outer one and can use everything that is in scope where it is defined, including the parameters of the outer function.

nested.fsx
let report (name: string) score maxScore =
    let percent () =
        float score / float maxScore * 100.0

    let grade () =
        let p = percent ()
        if p >= 90.0 then "A"
        elif p >= 75.0 then "B"
        elif p >= 50.0 then "C"
        else "F"

    printfn "%s: %d/%d (%.1f %%), grade %s" name score maxScore (percent ()) (grade ())

report "Lucia" 46 50
report "Peter" 31 50

The report function prints a score as a percentage and a grade. Two helper functions do the work.

let percent () =
    float score / float maxScore * 100.0

The helper takes no arguments of its own. It reads score and maxScore from the enclosing function, so they do not have to be passed to it.

let grade () =
    let p = percent ()

The second helper calls the first one. A local function can use the local functions defined above it. Neither helper is visible outside report. In the format string, %% prints a percent sign.

λ dotnet fsi nested.fsx
Lucia: 46/50 (92.0 %), grade A
Peter: 31/50 (62.0 %), grade C

Shadowing

A parameter or local value may have the same name as a value in an outer scope. The inner binding shadows the outer one: inside its scope, the name refers to the inner binding.

shadowing.fsx
let limit = 100

let clamp limit value =
    if value > limit then limit else value

let describe (name: string) =
    let name = name.Trim()
    let name = name.ToUpper()
    sprintf "[%s]" name

printfn "%d" (clamp 10 25)
printfn "%d" (clamp 10 7)
printfn "%s" (describe "  lucia ")
printfn "limit: %d" limit

The program shadows a top-level value with a parameter and a parameter with local values.

let clamp limit value =
    if value > limit then limit else value

The parameter limit shadows the top-level limit. Inside clamp, limit is the argument, 10 in our calls. The top-level value is unaffected and still prints 100.

let describe (name: string) =
    let name = name.Trim()
    let name = name.ToUpper()

Each line binds a new name computed from the previous one. Shadowing a parameter this way is a common idiom for cleaning up an argument; the original, untrimmed value cannot be used by mistake later in the function. The Trim method removes the whitespace from both ends of a string.

λ dotnet fsi shadowing.fsx
10
7
[LUCIA]
limit: 100

Closures capture values

A function remembers the bindings that were in scope where it was defined. Such a function is called a closure. Shadowing a name later does not change what the function sees.

captured.fsx
let rate = 0.2
let tax amount = amount * rate

do
    let rate = 0.5
    printfn "local rate: %.2f" rate
    printfn "tax on 100: %.2f" (tax 100.0)

let makeTax rate =
    fun amount -> amount * rate

let reduced = makeTax 0.1
let standard = makeTax 0.2

printfn "reduced tax on 100: %.2f" (reduced 100.0)
printfn "standard tax on 100: %.2f" (standard 100.0)

The tax function uses the top-level rate.

do
    let rate = 0.5
    printfn "local rate: %.2f" rate
    printfn "tax on 100: %.2f" (tax 100.0)

Inside the block, rate is shadowed with 0.5. The tax function still computes 20, because it refers to the binding that was visible where it was defined. Its meaning is fixed by the source code, not by the place from which it is called.

let makeTax rate =
    fun amount -> amount * rate

The lambda returned by makeTax captures the parameter rate. Each call to makeTax creates a new closure with its own rate, so reduced and standard compute different taxes. More on closures is in F# lambda.

λ dotnet fsi captured.fsx
local rate: 0.50
tax on 100: 20.00
reduced tax on 100: 10.00
standard tax on 100: 20.00

Loops and conditionals

The body of a for loop, a while loop, and each branch of an if expression are blocks. Values bound in them are local to the block.

blocks.fsx
let mutable total = 0

for i in 1 .. 5 do
    let square = i * i
    total <- total + square
    printfn "i = %d, square = %d" i square

let value = 17

if value % 2 = 1 then
    let half = value / 2
    printfn "%d is odd, %d + %d + 1" value half half

printfn "total: %d" total

The loop sums squares and the conditional splits an odd number.

for i in 1 .. 5 do
    let square = i * i
    total <- total + square

The loop variable i and the value square exist only in the body, and they are new in each iteration. A value that must survive the loop, such as total, has to be defined before the loop and be mutable.

if value % 2 = 1 then
    let half = value / 2

The half value belongs to the then branch. It is not visible in an else branch or after the expression.

λ dotnet fsi blocks.fsx
i = 1, square = 1
i = 2, square = 4
i = 3, square = 9
i = 4, square = 16
i = 5, square = 25
17 is odd, 8 + 8 + 1
total: 55

Definition order

A name can be used only after its binding. F# reads a file from top to bottom, and a binding cannot refer to a value that is defined further down.

order.fsx
let total = subtotal + 5

let subtotal = 20

The first binding uses subtotal, which is defined on the next line.

let total = subtotal + 5

The program does not compile; the error points to subtotal on line 1. Swapping the two lines fixes it. The same rule applies to functions: a function cannot call itself unless it is declared with let rec, and two functions that call each other are joined with and; see F# recursion. In a project, the order of the source files matters in the same way. The path of the file is shortened in the output.

λ dotnet fsi order.fsx
order.fsx(1,13): error FS0039: The value or constructor 'subtotal' is not defined.

Source

F# language reference: let Bindings

F# language reference: Functions

In this article we have looked at top-level and local values, nested functions, shadowing, closures, block scopes in loops and conditionals, and definition order. How the compiler works out the types of these bindings is covered in F# type inference, and mutable variables in F# mutability.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.