On this page:
#%index
#%index
Indexable
Mutable  Indexable
8.12

6.37 Indexables🔗ℹ

An indexable value is one that supports [] afterward to extract an element at the index within []. Maps, lists, arrays, sets, strings, and byte strings are all indexable, as are instances of classes that implement Indexable.

expression

expr #%index [at_expr]

 

expression

expr #%index [at_expr] assign_op rhs_expr

 

repetition

repet #%index [at_repet]

 

assign_op

 = 

:=

 | 

other_assign_op

Without an assign_op, accesses an element of an indexable, such as a map, array, list, string, or Indexable object. The element is accessed from the value produced by expr at the index or key produced by at_expr. The access form also works as a repetition given repetitions for a collection and an index.

With an assign_op, for a mutable indexable object (such as an array, map, set, or MutableIndexable object), the index element is assigned to the value based on the operator and rhs_expr. The expression result is #void in the case of := as assign_op.

See also use_static.

The #%index form is implicitly used when [] is used in after another expression or repetition in an expression or repetition position. See also Implicit Forms.

> {"a": 1, "b": 2}["a"]

1

> {"a": 1, "b": 2} #%index ["a"]

1

Provided only in the class space and annot space, not the namespace space.

An interface that a class can implement (publicly or privately) to make instances of the class work with #%index. As an annotation, Indexable matches all indexable objects, not just instances of classes that publicly implement the Indexable interface.

The interface has a single abstract method:

class Interleaved(lst1, lst2):

  private implements Indexable

  private override method get(index):

    if (index mod 2) == 0

    | lst1[index div 2]

    | lst2[index div 2]

> def lsts = Interleaved([1, 2, 3], [-1, -2, -3])

> lsts[2]

2

> lsts[3]

-2

Provided only in the class space and annot space, not the namespace space.

An interface that extends Indexable to add support for assignment with #%index. As an annotation, MutableIndexable matches all mutable indexable objects.

The interface has one additional abstract method:

  • set(index, val) takes an index and new val, which are the second and third arguments to #%index. Those arguments are normally written within [] and after an assignment operator like :=, respectively. The result must be #void.

class InterleavedArray(arr1, arr2):

  private implements MutableIndexable

  private override method get(index):

    if (index mod 2) == 0

    | arr1[index div 2]

    | arr2[index div 2]

  private override method set(index, val):

    if (index mod 2) == 0

    | arr1[index div 2] := val

    | arr2[index div 2] := val

> def lsts = InterleavedArray(Array(1, 2, 3), Array(-1, -2, -3))

> lsts[2] := 20

> lsts

InterleavedArray(Array(1, 20, 3), Array(-1, -2, -3))