6.20.1 Pairs

Asymptote has a builtin type for pairs of reals. To obtain a pair type for any two types, one can use the collections.genericpair(K,V) templated module. The fields are called k and v rather than x and y. The pair type is called Pair_K_V, which users are encouraged to rename based on the types being used. There is also a function makePair that creates a pair from two values; because of function overloading, the name of the function does not need to specify the two types.

Here’s an example:

from collections.genericpair(K=int, V=string) access
    Pair_K_V as Pair_int_string,
    makePair;
var p=makePair(3, 'hello');
write(p.k);  // Outputs 3
write(p.v);  // Outputs hello
var q = makePair(4, 'hello');
var s = makePair(3, 'world');
Pair_int_string t = makePair(3, 'hello');
assert(p != q);
assert(p != s);
assert(p == t);

Note that the == and != operators are overloaded for pairs, and the overloads are based on the == operators of the two types in the pair. An unfortunate consequence of this is that this module cannot be used for pairs of arrays, because the == operator for arrays returns a bool[] rather than a bool. See Wrapping arrays for a workaround.

The Pair_K_V type also has an int hash() method initialized to null. If you want to use pairs as keys in a hashmap, you should define this method, something like this:

from collections.genericpair(K=int, V=string) access
    Pair_K_V as Pair_int_string;
Pair_int_string p = makePair(3, 'hello');
p.hash = new int() {
  return hash(new int[] {p.k, p.v.hash()});
};

See Hash functions for more information.