Tuples

Some different uses of tuples in Roc.

A tuple is like a record, except instead of field names they have field positions. For example, instead of having foo.name to access the name field of a record, you might write foo.0 to acess the first field in a tuple (or foo.1 for the second field, etc.)

Code

app [main] { pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.10.0/vNe6s9hWzoTZtFmNkvEICPErI9ptji_ySjicO6CkucY.tar.br" }

import pf.Stdout
import pf.Task

main =

    # a tuple that contains different types
    simpleTuple : (Str, Bool, I64)
    simpleTuple = ("A String", Bool.true, 15_000_000)

    # access the items in a tuple by index (starts at 0)
    firstItem = simpleTuple.0
    secondItem = if simpleTuple.1 then "true" else "false"
    thirdItem = Num.toStr simpleTuple.2
    Stdout.line!
        """
        First is: $(firstItem),
        Second is: $(secondItem), 
        Third is: $(thirdItem).
        """

    # You can also use tuples with `when`:
    fruitSelection : [Apple, Pear, Banana]
    fruitSelection = Pear

    quantity = 12

    when (fruitSelection, quantity) is
        # TODO re-enable when github.com/roc-lang/roc/issues/5530 is fixed.
        # (_, qty) if qty == 0 ->
        #    Stdout.line "You also have no fruit."
        (Apple, _) ->
            Stdout.line "You also have some apples."

        (Pear, _) ->
            Stdout.line "You also have some pears."

        (Banana, _) ->
            Stdout.line "You also have some bananas."

Output

Run this from the directory that has main.roc in it:

$ roc run
First is: A String,
Second is: true,
Third is: 15000000.
You also have some pears.