ZetCode

F# generics

last modified December 3, 2026

In this article we write generic functions and types in F#.

Generic code works with values of many types. It has type parameters, written with an apostrophe, such as 'T, which are replaced by concrete types where the code is used. The list, option and Result types and most functions of the List module are generic. The compiler often makes functions generic without being asked; this automatic generalization is shown in F# type inference. This article covers type parameters that we declare ourselves.

Explicit type parameters

Type parameters can be written out, in angle brackets after the function name, or only in the parameter annotations. A caller may also give the type arguments explicitly.

explicit.fsx
let repeat<'T> (n: int) (value: 'T) : 'T list =
    List.replicate n value

let swap (a: 'T, b: 'U) = (b, a)

printfn "%A" (repeat 3 "ho")
printfn "%A" (repeat 2 1.5)
printfn "%A" (repeat<char> 4 'x')

printfn "%A" (swap (1, "one"))
printfn "%A" (swap ("on", true))

repeat builds a list of copies of any value, and swap swaps the items of a pair of any two types.

let repeat<'T> (n: int) (value: 'T) : 'T list =

The declaration says that repeat has one type parameter. The annotations then use it: the value has the type 'T and the result is a list of 'T.

printfn "%A" (repeat<char> 4 'x')

An explicit type argument is rarely needed, because the compiler infers it from the arguments. In swap, the type parameters appear only in the annotations. Such a function is generic as well, but it cannot be given explicit type arguments; swap<string, bool> would cause warning FS0686.

λ dotnet fsi explicit.fsx
["ho"; "ho"; "ho"]
[1.5; 1.5]
['x'; 'x'; 'x'; 'x']
("one", 1)
(true, "on")

Generic records

A record type can have type parameters, listed after its name. Each use of the record fills them in.

records.fsx
type Pair<'T> = { First: 'T; Second: 'T }

type Measurement<'T> = { Label: string; Value: 'T }

let flip pair = { First = pair.Second; Second = pair.First }

let p1 = { First = 1; Second = 2 }
let p2 = { First = "left"; Second = "right" }

printfn "%A" (flip p1)
printfn "%A" (flip p2)

let readings =
    [ { Label = "temperature"; Value = 21.5 }
      { Label = "humidity"; Value = 48.0 } ]

let status = { Label = "door"; Value = "closed" }

for r in readings do
    printfn "%s: %.1f" r.Label r.Value

printfn "%s: %s" status.Label status.Value

Pair holds two values of the same type, and Measurement pairs a label with a value of any type.

let flip pair = { First = pair.Second; Second = pair.First }

The flip function is generic too: its inferred type is Pair<'a> -> Pair<'a>. It works for pairs of numbers and pairs of strings.

let status = { Label = "door"; Value = "closed" }

readings is a Measurement<float> list, while status is a Measurement<string>. They are different types made from the same definition, so they cannot be put in one list.

λ dotnet fsi records.fsx
{ First = 2
  Second = 1 }
{ First = "right"
  Second = "left" }
temperature: 21.5
humidity: 48.0
door: closed

Generic unions

Unions take type parameters in the same way. The option type itself is a generic union with the cases Some and None. A recursive generic union describes a data structure that holds values of any type.

tree.fsx
type Tree<'T> =
    | Leaf
    | Node of left: Tree<'T> * value: 'T * right: Tree<'T>

let rec insert value tree =
    match tree with
    | Leaf -> Node(Leaf, value, Leaf)
    | Node(left, v, right) ->
        if value < v then Node(insert value left, v, right)
        elif value > v then Node(left, v, insert value right)
        else tree

let rec toList tree =
    match tree with
    | Leaf -> []
    | Node(left, v, right) -> toList left @ [v] @ toList right

let numbers = [42; 17; 8; 99; 23; 17] |> List.fold (fun t x -> insert x t) Leaf
let words = ["pear"; "apple"; "fig"; "kiwi"] |> List.fold (fun t x -> insert x t) Leaf

printfn "%A" (toList numbers)
printfn "%A" (toList words)

A binary search tree keeps smaller values on the left and larger ones on the right. The duplicate 17 is ignored.

let rec insert value tree =

The compiler infers the type 'a -> Tree<'a> -> Tree<'a> when 'a: comparison. Because insert compares values with < and >, it only accepts types that support comparison. This requirement is called a constraint.

λ dotnet fsi tree.fsx
[8; 17; 23; 42; 99]
["apple"; "fig"; "kiwi"; "pear"]

Generic classes

A class can have type parameters as well. Its members can use them in parameters, results and private fields.

stack.fsx
type Stack<'T>() =
    let mutable items: 'T list = []

    member _.Push(item: 'T) = items <- item :: items

    member _.Pop() =
        match items with
        | [] -> None
        | top :: rest ->
            items <- rest
            Some top

    member _.Count = items.Length

let numbers = Stack<int>()
numbers.Push 1
numbers.Push 2
numbers.Push 3
printfn "%A %A" (numbers.Pop()) (numbers.Pop())
printfn "count: %d" numbers.Count

let undo = Stack()
undo.Push "type 'a'"
undo.Push "delete line"
printfn "undo %A" (undo.Pop())

The stack stores its items in a private list. Pop returns an option, because the stack may be empty.

let undo = Stack()

The type argument can be left out when the compiler can infer it from later use. Here it becomes Stack<string> because strings are pushed onto it.

λ dotnet fsi stack.fsx
Some 3 Some 2
count: 1
undo Some "delete line"

Comparison and equality constraints

Constraints are written after when. The comparison constraint allows ordering with <, max and sorting; equality allows =. A type that declares a constraint passes it on to the code that uses it.

constraints.fsx
type TopList<'T when 'T: comparison>(size: int) =
    let mutable items: 'T list = []

    member _.Add(item: 'T) =
        items <- item :: items |> List.sortDescending |> List.truncate size

    member _.Items = items

let countOf (item: 'T) (items: 'T list) : int when 'T: equality =
    items |> List.filter (fun x -> x = item) |> List.length

let scores = TopList<int>(3)
for s in [72; 95; 61; 88; 99; 70] do
    scores.Add s
printfn "%A" scores.Items

let players = TopList<int * string>(2)
players.Add(31, "Anna")
players.Add(45, "Peter")
players.Add(28, "Zoe")
printfn "%A" players.Items

printfn "%d" (countOf "a" ["a"; "b"; "a"; "c"])

TopList keeps the largest few values added to it.

type TopList<'T when 'T: comparison>(size: int) =

The class sorts its items, so its type parameter must support comparison. Numbers, strings, tuples, records and unions of such types all do; tuples compare item by item.

let countOf (item: 'T) (items: 'T list) : int when 'T: equality =

The constraint of a function is written after its return type. Here the compiler would infer it anyway; writing it documents the requirement.

λ dotnet fsi constraints.fsx
[99; 95; 88]
[(45, "Peter"); (31, "Anna")]
2

Unsatisfied constraints

The compiler checks constraints where the generic code is used. A class without its own comparison does not support the comparison constraint.

no_comparison.fsx
type Box(weight: int) =
    member _.Weight = weight

let heaviest (items: 'T list) = List.max items

printfn "%d" (heaviest [3; 9; 4])
printfn "%A" (heaviest [Box 3; Box 9])

heaviest works for a list of integers but not for a list of boxes.

printfn "%A" (heaviest [Box 3; Box 9])

The error FS0193 is reported before the script runs, so even the first line prints nothing. A class supports comparison when it implements System.IComparable; often a function such as List.maxBy (fun b -> b.Weight) is the simpler fix.

λ dotnet fsi no_comparison.fsx
no_comparison.fsx(7,25): error FS0193: The type 'Box' does not support the 'comparison' constraint. For example, it does not support the 'System.IComparable' interface

Interface constraints

A constraint can require a type parameter to implement an interface, as in 'T :> IShape. The shorter form #IShape, called a flexible type, means "IShape or any type that implements it". This matters for collections: a list of circles is not a list of shapes.

flexible.fsx
type IShape =
    abstract Area: float

type Circle(r: float) =
    member _.Radius = r
    interface IShape with
        member _.Area = System.Math.PI * r * r

let totalArea (shapes: #IShape list) =
    shapes |> List.sumBy (fun s -> s.Area)

let largest (shapes: 'T list) : 'T when 'T :> IShape =
    shapes |> List.maxBy (fun s -> s.Area)

let circles = [Circle(1.0); Circle(2.5); Circle(0.5)]

printfn "total: %.2f" (totalArea circles)

let big = largest circles
printfn "largest radius: %.1f" big.Radius

Both functions work with a list of circles without converting it.

let totalArea (shapes: #IShape list) =

With the parameter type IShape list, the call would fail with error FS0001: the compiler converts single values to an interface, but not the elements of a list. The flexible type makes the function generic over the element type.

let largest (shapes: 'T list) : 'T when 'T :> IShape =

largest returns the same type it was given. The result is a Circle, so Radius can be read from it; a function returning IShape would lose that information. Interfaces are covered in F# interfaces.

λ dotnet fsi flexible.fsx
total: 23.56
largest radius: 2.5

Other constraints

F# has a few more constraints. The constructor constraint 'T: (new: unit -> 'T) requires a constructor without parameters, 'T: struct a value type, 'T: not struct a reference type, and 'T: null a type that has null as a value.

other_constraints.fsx
let createMany<'T when 'T: (new: unit -> 'T)> n =
    List.init n (fun _ -> new 'T())

let orDefault (value: 'T) (fallback: 'T) : 'T when 'T: null =
    if isNull value then fallback else value

let defaultOf<'T when 'T: struct> () = Unchecked.defaultof<'T>

let builders = createMany<System.Text.StringBuilder> 3
builders[0].Append("Hello there!") |> ignore
printfn "%d builders, first: %s" builders.Length (builders[0].ToString())

printfn "%s" (orDefault null "anonymous")
printfn "%s" (orDefault "Lucia" "anonymous")

printfn "%d %f %b" (defaultOf<int> ()) (defaultOf<float> ()) (defaultOf<bool> ())

Each function relies on one of the constraints.

List.init n (fun _ -> new 'T())

Only the constructor constraint allows new 'T(). The StringBuilder class has such a constructor, so three empty builders are created.

let orDefault (value: 'T) (fallback: 'T) : 'T when 'T: null =

isNull needs a type that may be null. Strings and .NET classes are such types; F# records, unions and numbers are not, and the compiler rejects them here.

λ dotnet fsi other_constraints.fsx
3 builders, first: Hello there!
anonymous
Lucia
0 0.000000 false

Inline functions

Arithmetic operators are not generic in the usual sense. A function such as let square x = x * x is inferred for int. Marking it inline makes the compiler copy the body into each call, so each call works with its own numeric type.

inline.fsx
let square x = x * x

let inline squareAny x = x * x

let inline average (xs: 'T list) =
    LanguagePrimitives.DivideByInt (List.sum xs) xs.Length

printfn "%d" (square 7)

printfn "%d" (squareAny 7)
printfn "%.2f" (squareAny 1.5)
printfn "%M" (squareAny 2.5m)

printfn "%.2f" (average [1.0; 2.5; 4.0])
printfn "%M" (average [10m; 20m; 45m])

square accepts only integers, while squareAny accepts any type with a * operator.

let inline squareAny x = x * x

The type of squareAny has a statically resolved type parameter, written ^a, with a member constraint that requires the * operator. Such constraints are checked at compile time for each call. Standard functions such as List.sum and List.average are inline for the same reason.

LanguagePrimitives.DivideByInt (List.sum xs) xs.Length

average sums the list and divides the sum by an integer count. DivideByInt works for floats and decimals, but not for integers, so average [1; 2] would not compile.

λ dotnet fsi inline.fsx
49
49
2.25
6.25
2.50
25

Member constraints

An inline function can require a type parameter to have a particular member, without any interface. The types only need a member with the right name and type.

members.fsx
type Square = { Side: float } with
    member this.Area = this.Side * this.Side

type Circle(r: float) =
    member _.Area = System.Math.PI * r * r

type Room = { Name: string; Area: float }

let inline areaOf<'T when 'T: (member Area: float)> (x: 'T) = x.Area

let inline describe (x: 'T when 'T: (member Area: float)) =
    $"{x.GetType().Name} {x.Area:F2}"

printfn "%.2f" (areaOf { Side = 3.0 })
printfn "%.2f" (areaOf (Circle(1.0)))
printfn "%.2f" (areaOf { Name = "kitchen"; Area = 12.5 })

printfn "%s" (describe (Circle(2.0)))
printfn "%s" (describe { Name = "hall"; Area = 6.0 })

A square record, a circle class and a room record are unrelated types; all three have an Area property.

let inline areaOf<'T when 'T: (member Area: float)> (x: 'T) = x.Area

The constraint asks for an Area property of type float. Because of the constraint, x.Area can be used inside the function. A record field counts as a property. Member constraints are best kept for small helpers; interfaces describe shared behaviour more clearly.

λ dotnet fsi members.fsx
9.00
3.14
12.50
Circle 12.57
Room 6.00

A generic repository

The last example is a generic class that stores items under a key. The key is computed from the item by a function given to the constructor, so the same class works for any record.

repository.fsx
type Repository<'Key, 'T when 'Key: comparison>(getKey: 'T -> 'Key) =
    let mutable items: Map<'Key, 'T> = Map.empty

    member _.Save(item: 'T) = items <- Map.add (getKey item) item items
    member _.TryFind(key: 'Key) = Map.tryFind key items
    member _.Remove(key: 'Key) = items <- Map.remove key items
    member _.All = items |> Map.toList |> List.map snd
    member _.Count = items.Count

type Book = { Isbn: string; Title: string; Year: int }
type Employee = { Id: int; Name: string; Team: string }

let books = Repository(fun (b: Book) -> b.Isbn)
books.Save { Isbn = "978-0441013593"; Title = "Dune"; Year = 1965 }
books.Save { Isbn = "978-0553283686"; Title = "Hyperion"; Year = 1989 }
books.Save { Isbn = "978-0441013593"; Title = "Dune"; Year = 1966 }

printfn "%d books" books.Count
match books.TryFind "978-0441013593" with
| Some b -> printfn "%s (%d)" b.Title b.Year
| None -> printfn "not found"

let staff = Repository(fun (e: Employee) -> e.Id)
for e in [ { Id = 3; Name = "Tomas"; Team = "web" }
           { Id = 1; Name = "Lucia"; Team = "data" }
           { Id = 2; Name = "Peter"; Team = "web" } ] do
    staff.Save e

staff.Remove 2
for e in staff.All do
    printfn "%d %s (%s)" e.Id e.Name e.Team
printfn "%A" (staff.TryFind 2)

One repository stores books by ISBN and another stores employees by number.

type Repository<'Key, 'T when 'Key: comparison>(getKey: 'T -> 'Key) =
    let mutable items: Map<'Key, 'T> = Map.empty

The keys of a Map must support comparison, so the 'Key parameter carries the constraint. The stored items need none.

let books = Repository(fun (b: Book) -> b.Isbn)

Both type arguments are inferred from the key function: Repository<string, Book> here and Repository<int, Employee> for the staff. Saving a book with an existing ISBN replaces the old entry, and All returns the items in key order.

λ dotnet fsi repository.fsx
2 books
Dune (1966)
1 Lucia (data)
3 Tomas (web)
None

Source

F# language reference: Generics

F# language reference: Constraints

F# language reference: Statically resolved type parameters

F# language reference: Flexible types

In this article we have declared type parameters on functions, records, unions and classes, used the comparison, equality, interface, constructor and null constraints, written inline functions and member constraints, and built a generic repository. Automatic generalization is covered in F# type inference, interfaces in F# interfaces, and maps in F# map.

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.