F# type extensions and operators
last modified December 4, 2026
In this article we add members to existing types in F# and define operators for our own types.
A type extension adds methods and properties to a type after its definition, even to a .NET type whose source we do not have. The extended type itself does not change: an extension cannot add fields or interfaces, and it sees only the public members. Operators, on the other hand, belong to the definition of a type; they are static members with symbolic names.
Intrinsic extensions
An extension in the same file and module as the type is intrinsic. It becomes part of the type, exactly as if the members were written in the type definition.
type Point = { X: float; Y: float }
let origin = { X = 0.0; Y = 0.0 }
type Point with
member p.Length = sqrt (p.X * p.X + p.Y * p.Y)
member p.Move(dx, dy) = { X = p.X + dx; Y = p.Y + dy }
let p = origin.Move(3.0, 4.0)
printfn "%A" p
printfn "length: %.1f" p.Length
The type Point with block adds a property and a method.
Between the definition and the extension we can write code that the
members need, such as origin; this is the usual reason for
an intrinsic extension.
λ dotnet fsi intrinsic.fsx
{ X = 3.0
Y = 4.0 }
length: 5.0
Optional extensions
An extension of a type defined elsewhere, for example in .NET, is
optional. It is visible only where the extension is in scope.
The type name may need its namespace or an open.
open System
type String with
member s.IsPalindrome =
let letters = s.ToLower() |> Seq.filter Char.IsLetter |> Array.ofSeq
letters = Array.rev letters
member s.Words = s.Split(' ', StringSplitOptions.RemoveEmptyEntries)
type Int32 with
member n.IsEven = n % 2 = 0
printfn "%b" "Never odd or even".IsPalindrome
printfn "%b" "falcon".IsPalindrome
printfn "%A" "an old hawk".Words
printfn "%b %b" (4).IsEven (7).IsEven
Inside the extension, the self identifier (s,
n) refers to the value the member is called on. An integer
literal needs parentheses before a member access, because
4. would start a floating-point number.
λ dotnet fsi optional.fsx true false [|"an"; "old"; "hawk"|] true false
Static members and properties
Extensions can add static members and properties with getters. Static members are called on the type name, like any other static member.
open System
type DateOnly with
member d.IsWeekend =
d.DayOfWeek = DayOfWeek.Saturday || d.DayOfWeek = DayOfWeek.Sunday
member d.FirstOfMonth = DateOnly(d.Year, d.Month, 1)
static member Parse8(text: string) =
DateOnly.ParseExact(text, "yyyyMMdd")
type TimeSpan with
static member FromWeeks(weeks: float) = TimeSpan.FromDays(7.0 * weeks)
let d = DateOnly.Parse8 "20261205"
printfn "%s weekend: %b" (d.ToString "yyyy-MM-dd") d.IsWeekend
printfn "first of month: %s" (d.FirstOfMonth.ToString "yyyy-MM-dd")
printfn "%A" (TimeSpan.FromWeeks 1.5)
Parse8 reads dates written as eight digits. It has a new
name because an extension never replaces an existing member: when both
have the same signature, the type's own member wins.
λ dotnet fsi static_ext.fsx 2026-12-05 weekend: true first of month: 2026-12-01 10.12:00:00
Extensions in a module
Extensions are usually placed in a module. Code that wants them opens
the module; without the open the members do not exist.
module TextExtensions =
type System.String with
member s.Truncate(width: int) =
if s.Length <= width then s else s.Substring(0, width - 3) + "..."
member s.Initials =
s.Split ' ' |> Array.map (fun w -> string w[0]) |> String.concat ""
module Report =
open TextExtensions
let line (name: string) (title: string) =
sprintf "%-4s %-20s" name.Initials (title.Truncate 20)
let books =
[ "Stanislaw Lem", "Solaris"
"Ursula Le Guin", "The Left Hand of Darkness"
"Frank Herbert", "Dune" ]
for name, title in books do
printfn "%s|" (Report.line name title)
Only the Report module opens TextExtensions, so
only its code can call Truncate and Initials.
Marking the extensions module with [<AutoOpen>] makes
them available wherever the parent namespace is opened; see
F# modules and namespaces.
λ dotnet fsi ext_module.fsx SL Solaris | ULG The Left Hand of ...| FH Dune |
Extending generic types
A generic type is extended with its type parameter. The F# list type is
List<'T>, and the option type is
Option<'T>.
type List<'T> with
member xs.Second = List.item 1 xs
member xs.IsSingle = List.length xs = 1
member xs.Pairs =
List.pairwise xs
type Option<'T> with
member o.Or(fallback: 'T) = Option.defaultValue fallback o
let birds = [ "owl"; "hawk"; "falcon" ]
printfn "%s" birds.Second
printfn "%b %b" birds.IsSingle [ 1 ].IsSingle
printfn "%A" [ 1; 4; 9 ].Pairs
let missing: int option = None
printfn "%d %d" ((Some 3).Or 0) (missing.Or 0)
The members work for a list of any element type. An optional extension cannot add constraints to the type parameter, so we cannot write a member that exists only on lists of numbers this way; the next sections show two alternatives.
λ dotnet fsi generic_ext.fsx hawk false true [(1, 4); (4, 9)] 3 0
Extending modules
In F# much of the functionality lives in modules such as
List and String. A module with the same name
adds functions to it; the new module is merged with the original for
name lookup.
module List =
let middle xs = List.item (List.length xs / 2) xs
module Option =
let ofTry (ok, value) = if ok then Some value else None
module String =
let words (s: string) = s.Split ' ' |> List.ofArray
printfn "%d" (List.middle [ 3; 8; 1; 9; 4 ])
printfn "%A" (List.map List.length [ [ 1 ]; [ 1; 2 ] ])
printfn "%A" (System.Int32.TryParse "42" |> Option.ofTry)
printfn "%A" (System.Int32.TryParse "x" |> Option.ofTry)
printfn "%A" (String.words "the owl and the hawk")
printfn "%s" (String.replicate 3 "ab")
List.middle and List.map are both available
through List; the same holds for the new
Option.ofTry, which turns the tuple from a
TryParse method into an option, and for
String.words next to String.replicate. Module
extensions are plain functions, so they can have any constraints.
λ dotnet fsi module_ext.fsx 1 [1; 2] Some 42 None ["the"; "owl"; "and"; "the"; "hawk"] ababab
Extension methods
.NET has its own extension methods, which C# uses. In F# they are
static methods marked with [<Extension>] in a type
marked with the same attribute. Unlike optional extensions, they can
target a specific instantiation of a generic type and are visible from
C#.
open System.Runtime.CompilerServices
[<Extension>]
type NumberExtensions =
[<Extension>]
static member Mean(xs: seq<float>) = Seq.average xs
[<Extension>]
static member Mean(xs: seq<int>) = xs |> Seq.map float |> Seq.average
[<Extension>]
static member Range(xs: seq<int>) = Seq.max xs - Seq.min xs
let temps = [ 21.5; 19.0; 23.5 ]
let scores = [| 78; 45; 91; 60 |]
printfn "%.2f" (temps.Mean())
printfn "%.2f" (scores.Mean())
printfn "%d" (scores.Range())
printfn "%d" ((seq { 1..10 }).Range())
The first parameter is the extended type. Because it is
seq<float> or seq<int>, the methods
work on lists, arrays, and sequences of those element types, and the
compiler picks the overload by the element type. A list of strings has
no Mean method.
λ dotnet fsi ext_methods.fsx 21.33 68.50 46 9
Extending interfaces
An interface can be extended as well. The extension members work on every type that implements the interface, using only the interface members.
type IShape =
abstract Name: string
abstract Area: float
type Circle(r: float) =
interface IShape with
member _.Name = "circle"
member _.Area = System.Math.PI * r * r
type Rect(w: float, h: float) =
interface IShape with
member _.Name = "rectangle"
member _.Area = w * h
type IShape with
member s.Describe() = sprintf "%s with area %.2f" s.Name s.Area
member s.IsLargerThan(other: IShape) = s.Area > other.Area
let shapes: IShape list = [ Circle 1.0; Rect(2.0, 3.0); Circle 2.0 ]
for s in shapes do
printfn "%s" (s.Describe())
printfn "%b" (shapes[0].IsLargerThan shapes[1])
Circle and Rect know nothing about
Describe. The extension adds a default behaviour for all
shapes without changing the interface, so existing implementations do
not have to be updated.
λ dotnet fsi interface_ext.fsx circle with area 3.14 rectangle with area 6.00 circle with area 12.57 false
Operators in a type
Operators for our own types are static members whose names are the
operator symbols in parentheses. A Zero property makes the
type usable with List.sum.
type Vector =
{ X: float; Y: float }
static member (+)(a: Vector, b: Vector) = { X = a.X + b.X; Y = a.Y + b.Y }
static member (-)(a: Vector, b: Vector) = { X = a.X - b.X; Y = a.Y - b.Y }
static member (*)(k: float, v: Vector) = { X = k * v.X; Y = k * v.Y }
static member (~-)(v: Vector) = { X = -v.X; Y = -v.Y }
static member Zero = { X = 0.0; Y = 0.0 }
override v.ToString() = sprintf "(%g, %g)" v.X v.Y
let a = { X = 1.0; Y = 2.0 }
let b = { X = 3.0; Y = -1.0 }
printfn "%O" (a + b)
printfn "%O" (a - b)
printfn "%O" (2.0 * a)
printfn "%O" (-b)
let path = [ a; b; { X = 0.5; Y = 0.5 } ]
printfn "%O" (List.sum path)
ToString gives the vectors a short form, which the
%O format prints. (~-) is the unary minus; the tilde marks the prefix
version of an operator. The (*) member takes the scalar
first, so 2.0 * a compiles but a * 2.0 does
not; adding the other order would need a second overload.
λ dotnet fsi vector.fsx (4, 1) (-2, 3) (2, 4) (-3, 1) (4.5, 1.5)
Extensions cannot add operators
An operator for a type we do not own cannot be added with an extension. The compiler warns about it and does not use the member.
type System.String with
static member (*)(s: string, n: int) = String.replicate n s
printfn "%s" ("ab" * 3)
The warning explains the rule, and the multiplication then fails,
because string still has no * operator. The
alternative is a custom operator, shown next.
λ dotnet fsi ext_operator.fsx ext_operator.fsx(2,19): warning FS1215: Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead. ext_operator.fsx(4,22): error FS0001: The type 'int' does not match the type 'string'
Custom operators
A new operator is defined with let like a function. Its
name is made of the characters !$%&*+-./<=>?@^|~.
The first characters decide the precedence and associativity: an
operator starting with * binds like multiplication.
let ( *. ) (s: string) (n: int) = String.replicate n s
let ( =~ ) (a: float) (b: float) = abs (a - b) < 1e-9
let ( |? ) (value: 'T option) (fallback: 'T) = Option.defaultValue fallback value
let ( </> ) (dir: string) (file: string) = System.IO.Path.Combine(dir, file)
printfn "%s" ("ab" *. 3)
printfn "%s" ("-" *. 2 + "|" + "-" *. 2)
printfn "%b %b" (0.1 + 0.2 = 0.3) (0.1 + 0.2 =~ 0.3)
printfn "%d" (None |? 10)
printfn "%s" ("home" </> "docs" </> "notes.txt")
*. starts with *, so in the second line it is
applied before +. Spaces inside ( *. ) keep
the parentheses from being read as a comment. Operators starting with
< are left-associative, so the path is built from left
to right. Custom operators make code short but can make it cryptic; use
a few well-named ones.
λ dotnet fsi custom_ops.fsx ababab --|-- false true 10 home/docs/notes.txt
A fluent report builder
The last example combines extensions and operators. A
Money type defines its arithmetic, and extension methods on
StringBuilder return the builder, so calls can be chained.
open System.Text
type Money =
{ Cents: int64 }
static member (+)(a: Money, b: Money) = { Cents = a.Cents + b.Cents }
static member (*)(n: int, m: Money) = { Cents = int64 n * m.Cents }
static member Zero = { Cents = 0L }
override m.ToString() = sprintf "%d.%02d" (m.Cents / 100L) (m.Cents % 100L)
let eur (amount: decimal) = { Cents = int64 (amount * 100m) }
type StringBuilder with
member sb.Line(text: string) = sb.AppendLine text
member sb.Rule() = sb.AppendLine(String.replicate 30 "-")
member sb.Row(label: string, value: obj) =
sb.AppendLine(sprintf "%-20s %9s" label (string value))
let items = [ "notebook", 3, eur 2.40m; "pen", 10, eur 0.95m; "folder", 2, eur 4.10m ]
let total = items |> List.sumBy (fun (_, qty, price) -> qty * price)
let report =
let sb = StringBuilder().Line("Invoice 2026-041").Rule()
for name, qty, price in items do
sb.Row(sprintf "%s x%d" name qty, qty * price) |> ignore
sb.Rule().Row("total", total).ToString()
printf "%s" report
Money is stored in cents to avoid rounding errors, and
ToString formats it. List.sumBy needs the
+ operator and the Zero property, both defined
in the type. Each StringBuilder extension returns the
builder that AppendLine returns, which allows the chained
calls; inside the loop we ignore the result.
λ dotnet fsi invoice.fsx Invoice 2026-041 ------------------------------ notebook x3 7.20 pen x10 9.50 folder x2 8.20 ------------------------------ total 24.90
Source
Type extensions - F# language reference
Operator overloading - F# language reference
In this article we have added members to our own types and to .NET
types with intrinsic and optional extensions, extended generic types,
modules, and interfaces, written extension methods with the
[<Extension>] attribute, defined operators as static
members, and created custom operators. Related articles are
F# classes,
F# interfaces, and
F# generics.
Author
List all F# tutorials.