Grav v1.14.0

Pair, Triple and Quad

import "std/collections" (included in import "std") · namespace std.collections

Pair<A, B>, Triple<A, B, C> and Quad<A, B, C, D> group two, three or four values. They are what the tuple syntax builds: (1, "one") is a Pair<int, string>, and the type (int, string) means Pair<int, string>. Their fields are first, second, third and fourth, and they cannot be changed after creation.

grav
import "std"

fn minMax(xs: Array<int>) -> (int, int) {
    let lo = xs[0]
    let hi = xs[0]
    for (x in xs) {
        if (x < lo) { lo = x }
        if (x > hi) { hi = x }
    }
    return (lo, hi)
}

fn main() {
    let r = minMax([4, 9, 1, 7])
    print(r)
    print(r.first)
    let (lo, hi) = r
    print(hi - lo)
    print(r.swap())
    print(r == (1, 9))
    let t = new Triple<string, int, bool>("x", 1, true)
    print(t.third)
}
Output
(1, 9)
1
8
(9, 1)
true
true

See Tuples and destructuring.

API

struct Entry<K, V>

A key and its value, as a map's iterator gives them: a value, not an object, so walking a map allocates nothing. for ((k, v) in map) takes it apart.

Fields

  • first: K // the key — the key
  • second: V // the value — the value

class Pair<A, B>

Constructors

  • new Pair(first: A, second: B)

Fields

  • readonly first: A
  • readonly second: B

Methods

  • fn swap() -> Pair<B, A> — A pair with the two values swapped.
  • fn operator==(o: Pair<A, B>) -> bool — Whether both values are equal (==).
  • fn toString() -> string — As text: (1, "a") (strings in quotes).

class Triple<A, B, C>

Constructors

  • new Triple(first: A, second: B, third: C)

Fields

  • readonly first: A
  • readonly second: B
  • readonly third: C

Methods

  • fn operator==(o: Triple<A, B, C>) -> bool — Whether all three values are equal (==).
  • fn toString() -> string — As text: (1, 2.5, "c") (strings in quotes).

class Quad<A, B, C, D>

Constructors

  • new Quad(first: A, second: B, third: C, fourth: D)

Fields

  • readonly first: A
  • readonly second: B
  • readonly third: C
  • readonly fourth: D

Methods

  • fn operator==(o: Quad<A, B, C, D>) -> bool — Whether all four values are equal (==).
  • fn toString() -> string — As text: (1, 2.5, "c", true) (strings in quotes).

Edit this page on GitHub