6.20.8 Wrapping arrays

Asymptote arrays have a builtin == operator that returns an array of bools rather than a single bool. This is useful in a number of contexts, but it also prevents them from being used in pairs or as values in hashmaps. The collections.wraparray(T) templated module provides a wrapper for arrays that has a more conventional == operator that returns a single bool. It also provides a hash() method that, if initialized, allows the array to be used as a key in a hashmap.

The main type in collections.wraparray(T) is Array_T. While Array_T is not a drop-in replacement for T[], it is as close as any structure can be. For convenience, the function Array_T wrap(T[] data) can be used to convert an array to an Array_T. Additionally, Array_T has autounraveled implicit casts to and from T[], so that it can be used in most places where T[] is expected (and vice versa). Note that these casts do not make copies, so if you modify the original array, the changes will be reflected in the Array_T and vice versa.

The methods and fields of Array_T are identical to those of T[], with the following exceptions:

int length()

is a method (requires parentheses afterwards) that returns the length of the array.

void cyclic(bool b)

sets the cyclic field of the wrapped array.

bool cyclic()

returns the cyclic field of the wrapped array.

int[] keys()

is a method (requires parentheses afterwards) that returns the keys field of the wrapped array.

T[] data

is a field that holds the wrapped array.

Additionally, the iteration syntax for (T x : a) is supported if a is an Array_T, as is element access a[i]. However, slices are not supported.

To make an Array_T hashable, pass a second argument to the wrap function that computes an integer hash of a single element. For instance, the following constructs hashable arrays of strings and integers:

from collections.wraparray(T=string) access Array_T as Array_string;
from collections.wraparray(T=int) access Array_T as Array_int;
string[] s = {'hello', 'world'};
Array_string ss = wrap(s, new int(string s) { return s.hash(); });
int[] a = {1, 2, 3};
Array_int aa = wrap(a, new int(int i) { return i; });

The resulting hash function works by converting all the elements of the array to integers using the provided function, and then hashing the resulting int[], see Hash functions.

Important note: If you use an Array_T as a key in a hashmap, you must ensure that the array is not modified while it is a key in the hashmap.