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.

Advertisements

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT BEST PRACTICES WITH MICROSOFT STACK & ANGULAR

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: