Declaring generic types in F#
March 19, 2017 Leave a comment
Generic types have type parameters in F#. This is no surprise to those coming from other languages like Java and C#. Generics increases the flexibility of objects by letting one or more of its properties take on multiple types.
In F# type parameters are declared using the single quote followed by the type name like here:
type Container<'a> = {description: string; containedValue: 'a}
If we declare a Container type like this…:
let intContainer = {description = "This is an int container"; containedValue = 5}
…then the contained value will be of type integer:
val intContainer : Container
It’s not required to declare the type parameter with a single character, like ‘a above, it’s just conventional to to do. The code works equally well with longer type names:
type Container<'containedType> = {description: string; containedValue: 'containedType}
We can as many generic types as we want. Here’s an example with 3 type parameters:
type Container<'a, 'b, 'c> = {description: string; first: 'a; second: 'b; third: 'c} let container = {description = "This is an int container"; first = 5; second = true; third = "hello world"}
type Container =
{description: string;
first: ‘a;
second: ‘b;
third: ‘c;}
val container : Container =
{description = “This is an int container”;
first = 5;
second = true;
third = “hello world”;}
View all F# related articles here.