liveBook · Manning

Generics

As explained in F# in Action: A Revised Edition of Get Programming with F#

A generic type is a type defined with one or more type parameters so it can apply to values of different concrete types.

Generics let a type or function work with values of different concrete types instead of being tied to one specific type. This removes casts and avoids separate CustomerList, IntList, or StringList implementations. section 3.2.3

F# often combines generics with type inference. You can provide a type argument explicitly, use a placeholder such as ResizeArray<_>, or let usage determine the type. Functions can also be automatically generalized when their arguments remain generic. section 3.2.3

A generic function can be written in two complementary styles:

  • Write the type parameter explicitly when the intended type is important: combineElements<int> 1 2 3. section 3.2.3
  • Let F# infer the generic behavior when the function is used consistently, as with combineElements 1 2 3. section 3.2.3
  • Keep the arguments type-consistent: passing a string to combineElements<int> produces a type error rather than silently accepting incompatible data. section 3.2.3

A function with inferred generic parameters

let greetPerson name age = $"Hello, {name}. You are {age} years old" F# reports the parameters using generic type variables, allowing calls such as greetPerson "Fred" 21. Changing the arguments lets you test the function repeatedly. section 2.5.5

let combineElements<'T> (a:'T) (b:'T) (c:'T) =   #1
    let output = ResizeArray<'T>()               #2
    output.Add a
    output.Add b
    output.Add c
    output
 
combineElements<int> 1 2 3                       #3

Inspect the complete explicit-generic example, including the type parameter, generic ResizeArray, and typed function call. section 3.2.3

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains generic types, explicit parameters, automatic generalization, inference, and resulting type errors through short examples.
Examples
Uses greeting functions, ResizeArray values, combineElements, explicit type arguments, omitted types, and a mismatched-type exercise.
What it assumes
Assumes basic F# function syntax and introduces generic notation, inference, and type annotations through small examples.
What you can do after
Build reusable F# functions and collections, choose explicit or inferred type arguments, and recognize incompatible-type errors.
How it connects
Connects generics with type inference, type annotations, automatic generalization, collections, and .NET.

Also explained in

Compare how 20 books explain generics →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.