// This worksheet demonstrates tuple types.
// A tuple is a collection of values surrounded by parentheses.
// We speak of "n-tuples" having n components. As a special case 2-tuples are called "pairs."
val p1 = (1, 3)
// When constructing a tuple any expression can be used for the components.
val x = 42
val y = 37
val p2 = (x + y, x - y)
// The components can have any type; the type of the tuple is related to the type of its components.
val p3 = ("Hello", 42, 3.14)
// Components can have arbitrarily structured types (such as tuples or Lists or whatever)
val p4 = (p1, p3)
val list1 = List( (1, 2), (3, 4), (5, 6) )
val p5 = (List(1, 2, 3), List(4, 5, 6))
val p6 = (List( (3.4, 2.7), (1.5, 5.9), (0.1, 5.8) ), "Hello")
// One of the primary uses of tuples is to allow an easy way for a method to return multiple things.
def addAndSubtract(x: Int, y: Int): (Int, Int) = {
(x + y, x - y)
}
addAndSubtract(5, 7)
// You can get at the components using the ._n notation. The first component is ._1.
p1._1
p1._2
p4._1._2
p4._2._3
// Pattern matching provides a more convenient (and more typical) way to get at the components.
val (sum, difference) = addAndSubtract(5, 7)
// The names bound in a tuple pattern act like ordinary vals (or vars if appropriate).
sum + 1
// Patterns can be complex. This matches a list of pairs against an elaborate pattern.
val ((head1, head2) :: tail, name) = p6