F#6 : Tuples

So our journey into F# continues. The next coupe of posts will be about F# types that may or may not have standard .NET equivalents. This post will be talking about tuples. What Are Tuples A tuple is a grouping of unnamed but ordered values, possibly of different types. Creating Tuples Tuples ar

So our journey into F# continues. The next coupe of posts will be about F# types that may or may not have standard .NET equivalents. This post will be talking about tuples.

What Are Tuples

A tuple is a grouping of unnamed but ordered values, possibly of different types.

Creating Tuples

Tuples are very easy to create, we simply do something like the following. Notice how I have created a mixed bag of tuples here, some are Ints, and others are strings, and we can also mix and match both the types and the number of values

And here is the results of running the above, where it can be seen that the someFunction function had no problem accepting and dealing with different typed tuples

Tuple Signatures

Up until now we have not touched on understanding F# signatures at all yet, it is in fact a topic i have decided to dedicate a whole blog post too, as I feel it is sufficiently complicated enough to warrant its own blog post. We are however where we are, which is the here and now, and we are exploring tuples, so for now I just wanted to demonstrate what a tuple signature would look like.

So we have seen how we can create tuples, but what about exploding or deconstructing them back into individual values. Is that possible? Yeah sure it is. As before lets start by looking at some examples:

There is also inbuilt support for obtaining the first and second values from a tuple. Which can be done using the “fst” and “snd” functions. There is no support for anything other than the 2st 2 (these are probably the most common cases). “fst” and “2nd” can be used as follows:

Now I want to draw your attention to a special case, which is when we may have a mismatch with the number of value that we are attempting to explode into individual values. So that would be something like the example here:

In fact if your tuples have different lengths and you are attempting to compare them using the equals operator “=” you will get a warning

Pattern Matting Tuples

We have not gone into pattern matching yet, but we will see an entire post on this subject later on. For now just know that it is a way to match again input parameters. You can do this against tuples, which is done as follows: