Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Language Basics

F# Tuples, Struct Tuples and the unit Type

Group values with F# tuples, take them apart by pattern, return several values from a function, use fst and snd, struct tuples, and understand unit, ignore and discards.

Two small ideas close the language basics: tuples, which group a few values without declaring a type, and unit, the type of "no value". Tuples show up everywhere in F#: functions return them, Map entries are tuples, List.zip produces them, and .NET methods with out parameters turn into them. This lesson shows how to build, read and compare tuples, and why unit exists.

Creating tuples

A tuple is a comma-separated group, usually in parentheses. Its type uses *, read as "and":

FSHARP
let pair = (1, "one")                    // int * string
let point = (3.5, -2.0)                  // float * float
let person = ("Ada", 36, true)           // string * int * bool

Elements may have different types, and the length is fixed. A tuple is immutable. (1, 2) and (1, 2, 3) are different types.

Taking tuples apart

The most idiomatic way is a pattern on the left of let:

FSHARP
let (name, age, active) = person
printfn "%s is %d" name age

Use _ to ignore an element:

FSHARP
let (_, years, _) = person

For pairs, the functions fst and snd return the first and second element:

FSHARP
fst (1, "one")     // 1
snd (1, "one")     // "one"

They only work on pairs (two elements). For larger tuples, use patterns.

Patterns also work in function parameters, so the function receives a tuple and unpacks it at once:

FSHARP
let distance (x1, y1) (x2, y2) =
    sqrt ((x2 - x1) ** 2.0 + (y2 - y1) ** 2.0)

printfn "%.1f" (distance (0.0, 0.0) (3.0, 4.0))    // 5.0

Returning several values

Instead of a custom class or out parameters, return a tuple:

FSHARP
let minMax numbers =
    (List.min numbers, List.max numbers)

let (lo, hi) = minMax [ 4; 9; 2; 7 ]
printfn "%d to %d" lo hi          // 2 to 9

A second example: .NET methods with out parameters are turned into tuples for you, which is why the TryParse pattern from Operators and type conversion matched on true, value.

FSHARP
let ok, number = System.Int32.TryParse "123"

Comparing and swapping

Tuples support structural equality and ordering (first element compared first):

FSHARP
(1, "a") = (1, "a")        // true
(1, "z") < (2, "a")        // true
compare (2, 1) (2, 3)      // -1

This makes tuples handy as keys in a Map or Set (for example, grid coordinates), and for sorting by several fields: List.sortBy (fun p -> (p.Last, p.First)) people.

Swapping two values needs no temporary:

FSHARP
let swap (a, b) = (b, a)
swap (1, "x")      // ("x", 1)

Struct tuples

Normal tuples are reference types (objects on the heap). In hot code that creates millions of tuples, a struct tuple avoids allocation. Add the struct keyword:

FSHARP
let p = struct (3, 4)
let struct (x, y) = p

Struct tuples are also what C# calls ValueTuple, so use them when you call C# code that takes or returns (int, int). For everyday work, ordinary tuples are fine.

Tuples are great for two or three values that travel together briefly. When the group has a meaning of its own, or has more than three elements, give it a record (see the next chapter) so every field has a name.

The unit type

unit has exactly one value, written (). It is what a function returns when it exists only for its effect:

FSHARP
let sayHi () = printfn "Hi!"       // unit -> unit
sayHi ()

The () in the definition means "takes no useful input", and the call passes (). You need this to define a function with no arguments, because let sayHi = printfn "Hi!" would just run the print once and bind the result.

Rules that follow from unit:

  • A statement in the middle of a block must be unit. If it is not, the compiler warns that you are discarding a value. Use ignore to do it on purpose: list.Remove 3 |> ignore.
  • An if without else must be unit.
  • for and while bodies are unit.
  • A function that returns unit and one that returns int are different shapes; do not mix them in branches.
FSHARP
let logAndReturn x =
    printfn "got %d" x       // unit, fine
    x * 2                    // the result

Discards

Besides _ in patterns, you can discard a computed result with let _ = expr or expr |> ignore. Prefer ignore because it reads left to right in pipelines.

Run the idea in C#

C# value tuples behave like F# tuples: positional, structural equality, deconstruction. void is the rough counterpart of unit.

C# C# stand-in: returning two values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: swapping and sorting by a tuple key

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of ("Ada", 36, true)?

    Tuple types are written with * between the element types.
  2. 2. What does snd (1, "one") return?

    snd returns the second element of a pair.
  3. 3. What is the value of type unit?

    unit has one value, written (). Functions with only side effects return it.
  4. 4. How do you discard a non-unit result on purpose?

    expr |> ignore throws the result away without a compiler warning.

Summary

  • Tuples group a fixed number of values of any types; the type is a * b * c.
  • Deconstruct with patterns; fst and snd work on pairs only.
  • Return a tuple to give back several values; .NET out parameters arrive as tuples.
  • Struct tuples avoid heap allocation and match C# ValueTuple.
  • unit is the "no value" type; use () for no-argument functions and ignore to discard.

Next: Defining functions