bitwise shrub/kav / lib / pair.kav
 1use <bool.kav> as bool
 2
 3/%
 4Builds a pair from two values.
 5
 6Consumes `x` and `y` and moves them into the tuple.
 7%/
 8pub fn make[a: type, b: type](x: a, y: b) -> (a, b) {
 9    (x, y)
10}
11
12/%
13Returns the first component of a pair.
14%/
15pub fn fst[a: utype, b: utype](pair: !(a, b)) -> a {
16    case pair of {
17    | (x, _) => x
18    }
19}
20
21/%
22Returns the second component of a pair.
23%/
24pub fn snd[a: utype, b: utype](pair: !(a, b)) -> b {
25    case pair of {
26    | (_, x) => x
27    }
28}
29
30/%
31Returns a new pair with the components swapped.
32%/
33pub fn swap[a: type, b: type](pair: (a, b)) -> (b, a) {
34    case pair of {
35    | ~(x, y) => (y, x)
36    }
37}
38
39/%
40Tests whether two integer pairs are equal.
41%/
42pub fn equal(pair1: !(int, int), pair2: !(int, int)) -> bool {
43    case (pair1, pair2) of {
44    | ((x1, y1), (x2, y2)) => bool::and(x1 == x2, y1 == y2)
45    }
46}
47
48/%
49Applies `f` to the first element of a pair.
50%/
51pub fn mapfst[a: type, b: type, c: type](pair: (a, b), f: fn(a) -> c) -> (c, b) {
52    case pair of {
53    | ~(x, y) => (f(x), y)
54    }
55}
56
57/%
58Applies `f` to the second element of a pair.
59%/
60pub fn mapsnd[a: type, b: type, c: type](pair: (a, b), f: fn(b) -> c) -> (a, c) {
61    case pair of {
62    | ~(x, y) => (x, f(y))
63    }
64}
65
66/%
67Applies `f` to the first and `g` to the second component of a pair.
68%/
69pub fn map[a: type, b: type, c: type, d: type](pair: (a, b), f: fn(a) -> c, g: fn(b) -> d) -> (c, d) {
70    case pair of {
71    | ~(x, y) => (f(x), g(y))
72    }
73}
74