Basics 03 - Tuples

Time to discuss tuples.

Learning-FSharp/Ch03-Tuples/Program.fs

Check out all the comments that are placed in the source file.

Key Ideas

  1. Tuples allow the grouping of data without involving structures/classes/records etc.

  2. Tuples, also known as Product Types in F#, have the signature: Type1 * Type2 * ... * TypeN

  3. (1, "two", 3.0) is a tuple with an int, a string, and a float; (int * string * float)

  4. Tuples, like basic data types, can be passed to functions as parameters and can be the return value of functions

  5. Tuple construction: let tup = (1, "two", 3.0)

  6. Extracting values from a tuple, also known as tuple deconstruction via pattern matching: let (x, y, z) = (1, "One", 1.0); more on pattern matching later

  7. A function with accepts a tuple as a parameter: let add (x, y, z) = x + y + z; signature being: (int * int * int ) -> int

  8. A function that returns a tuple: let combineAsTuple x y z = (x, y, z); signature being: int -> int -> int -> (int * int * int)

  9. .NET supports 2 types of tuples, Value Tuples (follow value semantics) and Reference Tuples (follow reference semantics)

  10. When working in C#, (a, b, c) creates a value tuple

  11. When working in F#, (a, b, c) creates a reference tuple

  12. When interoperating with C# code or .NET framework library or a third-party library, make sure to use the proper type

  13. Constructing value tuple: let structTupV1 = struct (1, "One", 1.0)

  14. Deconstructing value tuple: let struct (x, y, z) = struct (1, "One", 1.0)

If you have reached so far, congratulations.

Keep reading!