Collections

SPL has three built-in collections (list, set, and map).

The three built-in collections (list, set, and map) have the following type constructors.

Table 1. Constructors of built-in collections

The table lists constructors of the SPL collections.

Constructor Collection
list<T> list (random-access zero-indexed sequence)
set<T> set (unordered collection without duplicates)
map<K,V> map (unordered mapping from key type K to value type V)
list<T>[n] like list<T>, but bounded-length
set<T>[n] like set<T>, but bounded-length
map<K,V>[n] like map<K,V>, but bounded-length

Collections in SPL have bounded-length variants that follow the same rules as bounded strings. For example, list<int32>[2] can store a maximum of two integers. You can declare bounded-size types with unbounded elements, such as list<rstring>[3], though doing so does not offer the same marshalling optimization opportunities. SPL limits all bounded or unbounded collections to a maximum of 231-1 elements. For types with bounded size, the bounds must be compile-time constants.

The literal syntax for list values and map values is the same as in Python or JavaScript (including JSON), and the literal syntax for set values is similar to Python or JavaScript.

listLiteral ::= ‘[' expr*,]'                   # for example, [0, x, x+1, x+2]
mapLiteral  ::= ‘{' ( expr:' expr )*,}'      # for example, { "Mon": -1, "Fri": 1 }
setLiteral  ::= ‘{ ' expr*, }'                 # for example, { "Teracloud", "GOOG"}

List, set, and map types can be arbitrarily nested. In other words, their elements, and in the case of maps even their keys, can be of any type, including other composite types. Empty list, set, and map literals can occur only where their type is clear from the context: casts, variable initializers, assignments, and typed operator parameters.

Composite types have their own operators. For more information, see Expression language. You can subscript a list or map with l[i], check membership in a collection with "x in s", iterate over a collection with "for(T x in s) ...", and so on. There are also various functions to work on collections; for example, setUnion(set1, set2) or setIntersection(set1, set2).For maps, the left operand of the in operator is the key. In other words, "Oz" in m checks whether "Oz" is a key of the map m. Value (as opposed to key) membership tests use functions, not the in operator.

Note: Lists are implemented with arrays, but unlike the C language, SPL uses static or dynamic checks to protect against out-of-bounds accesses. Sets and maps are implemented with hash tables. They are unordered and support constant-time lookup.