Skip to main content

Introduction

Hack includes diverse range of array-like data structures.

Hack arrays are value types for storing iterable data. The types available are vec, dict and keyset. When in doubt, use Hack arrays.

Hack collections are deprecated object types for storing iterable data. The types available include Vector, Map, Set, Pair and helper interfaces.

Quick Start

You can create Hack arrays as follows:

$v = vec[2, 1, 2];

$k = keyset[2, 1];

$d = dict['a' => 1, 'b' => 3];

The Hack Standard Library

There are many helpful functions in the C, Vec, Keyset and Dict namespaces, which are a part of the Hack Standard Library (HSL).

For more information on included HSL namespaces, see Hack Standard Library: Namespaces.

// The C namespace contains generic functions that are relevant to
// all array and collection types.
C\count(vec[]); // 0
C\is_empty(keyset[]); // true

// The Vec, Keyset and Dict namespaces group functions according
// to their return type.
Vec\keys(dict['x' => 1]); // vec['x']
Keyset\keys(dict['x' => 1]); // keyset['x']

Vec\map(keyset[1, 2], $x ==> $x + 1); // vec[2, 3]

Arrays Cheat Sheet

Operationvecdictkeyset
Initialize empty$v = vec[];$d = dict[];$k = keyset[];
Literal$v = vec[1, 2, 3];$d = dict['foo' => 1];$k = keyset['foo', 'bar'];
From Another Container*$v = vec($container);$d = dict($keyed_container);$k = keyset($container);
Keys from Container*$v = Vec\keys($container);N/A$k = Keyset\keys($container);
Add Elements$v[] = 4;$d['baz'] = 2;$k[] = 'baz';
Bulk Add Elements$v = Vec\concat($t1, $t2)$d = Dict\merge($kt1, $kt2)$k = Keyset\union($t1, $t2)
Remove ElementsRemove-at-index is unsupported; Vec\drop($v,$n), Vec\take($v,$n); $first=C\pop_front(inout $x), $last=C\pop_back(inout $x)unset($d['baz']);unset($k['baz']);
Key ExistenceC\contains_key($v, 1)C\contains_key($d, 'foo')C\contains_key($k, 'foo')
Value ExistenceC\contains($v, 3)C\contains($d, 2)Use C\contains_key($k, 'foo')
Equality (Order-Dependent)$v1 === $v2$d1 === $d2$k1 === $k2
Equality (Order-Independent)N/ADict\equal($d1, $d2)Keyset\equal($k1, $k2)
Count Elements (i.e., length, size of array)C\count($v)C\count($d)C\count($k)
Type Signaturevec<Tv>dict<Tk, Tv>keyset<Tk>
Type Refinement$v is vec<_>$d is dict<_, _>$k is keyset<_>
Awaitable ConsolidationVec\from_async($v)Dict\from_async($d)Keyset\from_async($x)

* $container can be a Hack Array or Hack Collection

Arrays Conversion Cheat sheet

Prefer to use Hack arrays whenever possible. When interfacing with legacy APIs that expect older Containers, it may be easier to convert. Here's how:

ConvertingTo VectorTo MapTo Set
dictN/Anew Map($d)N/A
dict keysVector::fromKeysOf($d)N/ASet::fromKeysOf($d)
dict valuesnew Vector($d)N/Anew Set($d)
vecnew Vector($v)new Map($v)new Set($v)
keysetnew Vector($k)new Map($k)new Set($k)