F# modules and namespaces
last modified December 2, 2026
In this article we organize F# code with modules and namespaces.
A module is a named group of values, functions and types. It
keeps related code together and gives its members a common prefix, so that
names from different parts of a program do not clash. The standard library
is built this way: List.map is the map function
of the List module. A namespace groups modules and
types at a higher level, mostly across the files of a project.
Defining a module
A module is declared with the module keyword, a name and an
equals sign. Its contents are indented.
module Geometry =
let pi = 3.14159
let circleArea r = pi * r * r
let rectangleArea w h = w * h
printfn "%.2f" (Geometry.circleArea 2.0)
printfn "%.2f" (Geometry.rectangleArea 3.0 4.5)
printfn "%.5f" Geometry.pi
The Geometry module holds a value and two functions. Outside
the module, its members are accessed with the module name and a dot.
λ dotnet fsi first_module.fsx 12.57 13.50 3.14159
Opening a module
The open declaration makes the members of a module available
without the prefix.
module Temperature =
let toFahrenheit c = c * 1.8 + 32.0
let toCelsius f = (f - 32.0) / 1.8
open Temperature
printfn "%.1f" (toFahrenheit 21.0)
printfn "%.1f" (toCelsius 98.6)
printfn "%.1f" (Temperature.toCelsius 451.0)
open System
printfn "%.3f" (Math.Sqrt 2.0)
printfn "%s" (String.Join(", ", ["a"; "b"; "c"]))
After open Temperature, the functions can be called by their
short names. The qualified name still works.
open System
open also opens .NET namespaces. System contains
the Math and String classes. Opening is a
convenience; a module that is used only once or twice is often clearer with
the full name.
λ dotnet fsi open_module.fsx 69.8 37.0 232.8 1.414 a, b, c
Nested modules and types
A module can contain types and other modules. Nesting builds a small hierarchy of names.
module Shop =
type Item = { Name: string; Price: decimal }
module Pricing =
let vatRate = 0.20m
let withVat item = item.Price * (1m + vatRate)
module Basket =
let total items = items |> List.sumBy Pricing.withVat
let names items = items |> List.map (fun i -> i.Name)
let basket : Shop.Item list =
[ { Name = "kettle"; Price = 35.00m }
{ Name = "teapot"; Price = 18.50m } ]
printfn "%A" (Shop.Basket.names basket)
printfn "%.2f" (Shop.Pricing.withVat basket[0])
printfn "%.2f" (Shop.Basket.total basket)
The Shop module contains a record type and two nested modules.
let total items = items |> List.sumBy Pricing.withVat
Inside Shop, the sibling module is reachable as
Pricing. From outside, the full path is
Shop.Pricing.withVat.
let basket : Shop.Item list =
The record type is also qualified with the module name. The annotation tells the compiler which record the field names belong to.
λ dotnet fsi nested.fsx ["kettle"; "teapot"] 42.00 64.20
Private members
By default, everything in a module is public. The private
keyword hides helper values and functions, so that only the module itself
can use them.
module Password =
let private minLength = 8
let private hasDigit (s: string) =
s |> Seq.exists System.Char.IsDigit
let isStrong (s: string) =
s.Length >= minLength && hasDigit s
printfn "%b" (Password.isStrong "falcon")
printfn "%b" (Password.isStrong "falcon2026")
printfn "%b" (Password.hasDigit "abc1")
The public isStrong function uses two private helpers. The
last line tries to call a private function from outside the module, and the
script is not run.
λ dotnet fsi private_members.fsx private_members.fsx(12,15): error FS1094: The value 'hasDigit' is not accessible from this code location
Name clashes
When two opened modules define the same name, the module opened last wins. This can silently change which function is called, so some modules forbid being opened.
module Metric =
let distance km = $"{km} km"
module Imperial =
let distance miles = $"{miles} mi"
open Metric
open Imperial
printfn "%s" (distance 10)
printfn "%s" (Metric.distance 10)
[<RequireQualifiedAccess>]
module Log =
let info msg = printfn "[info] %s" msg
let warn msg = printfn "[warn] %s" msg
Log.info "starting"
Log.warn "disk almost full"
Both modules have a distance function.
open Metric open Imperial printfn "%s" (distance 10)
The unqualified distance refers to Imperial,
because it was opened last. The qualified name always says which one is
meant.
[<RequireQualifiedAccess>] module Log =
The RequireQualifiedAccess attribute makes
open Log an error; the members must be called as
Log.info. The List, Seq and
Option modules use this attribute, because names such as
map or filter would clash.
λ dotnet fsi clashes.fsx 10 mi 10 km [info] starting [warn] disk almost full
Opening a module automatically
The opposite attribute, AutoOpen, opens a module as soon as
its parent is opened or loaded. It suits small helpers that are used
everywhere.
[<AutoOpen>]
module Helpers =
let clamp lo hi x = max lo (min hi x)
let percent part total = 100.0 * float part / float total
printfn "%d" (clamp 0 10 15)
printfn "%d" (clamp 0 10 -3)
printfn "%.1f%%" (percent 17 40)
The functions of Helpers are available without an
open declaration. Use the attribute sparingly: names that
appear from nowhere make code harder to read.
λ dotnet fsi auto_open.fsx 10 0 42.5%
A module for a type
A common pattern pairs a type with a module of the same name that holds its
functions, like the list type and the List
module. The module comes after the type.
type Money = { Amount: decimal; Currency: string }
module Money =
let create currency amount = { Amount = amount; Currency = currency }
let add a b =
if a.Currency <> b.Currency then Error "different currencies"
else Ok { a with Amount = a.Amount + b.Amount }
let format m = $"{m.Amount:N2} {m.Currency}"
let price = Money.create "EUR" 1250.5m
let fee = Money.create "EUR" 9.9m
let refund = Money.create "USD" 30m
match Money.add price fee with
| Ok total -> printfn "%s" (Money.format total)
| Error e -> printfn "error: %s" e
match Money.add price refund with
| Ok total -> printfn "%s" (Money.format total)
| Error e -> printfn "error: %s" e
The Money record and the Money module share a
name. F# compiles the module under the name MoneyModule, but
in F# code we write Money.add. The add function
returns a Result, since amounts in
different currencies cannot be added.
λ dotnet fsi money.fsx 1,260.40 EUR error: different currencies
Loading another script
A script can load code from another script with the #load
directive. The loaded file becomes a module named after the file, with the
first letter capitalized.
let mean (xs: float list) = List.sum xs / float xs.Length
let variance (xs: float list) =
let m = mean xs
xs |> List.averageBy (fun x -> (x - m) ** 2.0)
let stdDev xs = sqrt (variance xs)
The stats.fsx file contains three statistical functions and no
module declaration.
#load "stats.fsx" open Stats let temperatures = [18.5; 21.0; 19.5; 24.0; 22.5; 17.0] printfn "mean: %.2f" (mean temperatures) printfn "std dev: %.2f" (stdDev temperatures) printfn "variance: %.2f" (Stats.variance temperatures)
The #load path is relative to the loading script. The module
Stats is then used like any other module.
λ dotnet fsi report.fsx mean: 20.42 std dev: 2.37 variance: 5.62
Modules in a project
In a project, each .fs file starts with a top-level module or
a namespace declaration. A top-level module is declared without the equals
sign, and the rest of the file belongs to it. The last file is the entry
point and may omit the declaration. The project is set up like the one in
the introduction.
module Shapes
type Shape =
| Circle of float
| Square of float
let area shape =
match shape with
| Circle r -> System.Math.PI * r * r
| Square a -> a * a
let describe shape =
match shape with
| Circle r -> $"circle with radius {r}"
| Square a -> $"square with side {a}"
The Shapes.fs file defines the Shapes module with
a union type and two functions.
open Shapes
let shapes = [Circle 1.0; Square 3.0; Circle 2.5]
for s in shapes do
printfn "%s: %.2f" (describe s) (area s)
Program.fs opens the module and uses it.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net11.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Shapes.fs" />
<Compile Include="Program.fs" />
</ItemGroup>
</Project>
The project file lists Shapes.fs before
Program.fs. The order matters: a file can only use the
modules of the files listed above it.
λ dotnet run circle with radius 1: 3.14 square with side 3: 9.00 circle with radius 2.5: 19.63
Namespaces
A namespace groups modules and types under a common name, usually the name of a library or an application. Unlike a module, a namespace cannot contain values or functions directly, and it can be spread over several files.
namespace Library
type Book = { Title: string; Author: string; Year: int }
type Loan = { Book: Book; Reader: string; Days: int }
Domain.fs puts two record types into the
Library namespace.
namespace Library
module Loans =
let isOverdue loan = loan.Days > 21
let fine loan =
if isOverdue loan then decimal (loan.Days - 21) * 0.25m else 0m
Loans.fs adds a module to the same namespace. Functions must
live in a module, so the module is declared with an equals sign inside the
namespace.
open Library
let book = { Title = "Dune"; Author = "Frank Herbert"; Year = 1965 }
let loans =
[ { Book = book; Reader = "Marek"; Days = 12 }
{ Book = book; Reader = "Jana"; Days = 30 } ]
for loan in loans do
printfn "%s: overdue %b, fine %.2f" loan.Reader (Loans.isOverdue loan) (Loans.fine loan)
One open Library brings in the types and the
Loans module from both files. The project file lists
Domain.fs, Loans.fs and Program.fs
in this order; otherwise it is the same as above.
λ dotnet run Marek: overdue false, fine 0.00 Jana: overdue true, fine 2.25
Source
F# language reference: Modules
F# language reference: Namespaces
In this article we have defined and opened modules, nested them, hidden
private members, handled name clashes with RequireQualifiedAccess
and AutoOpen, loaded scripts with #load, and used
top-level modules and namespaces in a project. Projects are introduced in
Introduction to F#, functions in
F# functions, and the next topic,
F# exceptions, uses modules for its
examples.
Author
List all F# tutorials.