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
Tuples allow the grouping of data without involving structures/classes/records etc.
Tuples, also known as Product Types in F#, have the signature:
Type1 * Type2 * ... * TypeN
(1, "two", 3.0)
is a tuple with anint
, astring
, and afloat
;(int * string * float)
Tuples, like basic data types, can be passed to functions as parameters and can be the return value of functions
Tuple construction:
let tup = (1, "two", 3.0)
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 laterA function with accepts a tuple as a parameter:
let add (x, y, z) = x + y + z
; signature being:(int * int * int ) -> int
A function that returns a tuple:
let combineAsTuple x y z = (x, y, z)
; signature being:int -> int -> int -> (int * int * int)
.NET supports 2 types of tuples, Value Tuples (follow value semantics) and Reference Tuples (follow reference semantics)
When working in C#,
(a, b, c)
creates a value tupleWhen working in F#,
(a, b, c)
creates a reference tupleWhen interoperating with C# code or .NET framework library or a third-party library, make sure to use the proper type
Constructing value tuple:
let structTupV1 = struct (1, "One", 1.0)
Deconstructing value tuple:
let struct (x, y, z) = struct (1, "One", 1.0)
If you have reached so far, congratulations.
Keep reading!