Lesson 9. Shaping data with tuples

 

You’ll start this unit by looking at the simplest data structure in F#, the tuple. Tuples are a great way to quickly pass small bits of data around your code when classes or similar elements feel like overkill. In this lesson

  • You’ll see how tuples are used within F#.
  • You’ll understand when to use and not use them.
  • You’ll see how tuples work together with type inference to enable succinct code.
  • You’ll see how tuples relate to the rest of .NET.

9.1. The need for tuples

Let’s start by considering an example that seems trivial and yet gets us in all sorts of contortions nearly every day. The following method takes in a string that contains an individual’s name (for example, "Isaac Abraham") and splits it into its constituent parts, returning both the forename and surname.

Listing 9.1. Trying to return arbitrary data pairs in C#
public ??? ParseName(string name) {
    var parts = name.Split(' ');
    var forename = parts[0];
    var surname = parts[1];
    return ???; }

What should this method return? There are a few options, none of which is particularly satisfying (I should point out that these are all real answers that have been suggested to me when I’ve posed this question!):

9.2. Tuple basics

9.3. More-complex tuples

9.4. Tuple best practices

Summary