-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
This is a part of the Hack array proposal
A keyset
is a set that can only contain valid array keys. It is implemented as a dict
whose values and keys are the same. For example:
$set = keyset[1, 2, 3];
// Logically expands to
dict[
1 => 1,
2 => 2,
3 => 3,
]
This will be an array at runtime with extra restrictions to allow it to be used safely like a Set
from the type checkers perspective. This focuses mainly on the desired runtime behavior, but if there are questions for how it will interact with the type checker I'll be happy to discuss.
Literal Constructor
A keyset
is constructed using the literal expression keyset[]
.
$set = keyset[]; // Empty set-array
$set = keyset['a', 'b', 'c']; // set-array of 3 elements
This is a static expression, so it can be used in a static initializer.
class C {
public static $set = keyset['a', 'b', 'c'];
}
Traversable Constructor
A keyset
can also be constructed from any Traversable
type, using the traversable constructor.
We will also have a function keyset_from_keys
to construct a keyset
from the keys of a KeyedTraversable
.
$array = array('a', 'b', 'c');
$set = keyset($array); // constructs set-array from another array
Checking Membership
isset
is used to check membership in a keyset
$set = keyset[4, 5, 6];
isset($set[0]);
Adding Elements
To add a new element to a keyset
we will introduce a new “set append” operator. From the type checkers perspective setting a key directly will be an error, but the runtime will behave the same as a dict
.
$set = keyset[];
$set{} = 2; // "Set-append" that sets (2 => 2) in $set
$set[$x] = 4; // Type error, but not a runtime error
Removing Elements
Removing an element from a keyset
is identical to removing an element from a PHP array by using the unset
function.