Declaring generic types in F#

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: